跳到主要内容

browser

2023年08月20日
柏拉文
越努力,越幸运

一、认识


浏览器原生机制下同样可以加载 ESModule, 那么是如何加载的呢?

二、语法


2.1 <script type="module" src="xx 依赖路径"></script>

<script type="module" src="./a.js">
b();
</script>

2.2 <script type="module"> import xx from 'xx 依赖路径' </script>


<script type="module">
import { b } from './b.js';
b();
</script>

2.3 <script type="importmap"> { "imports": { "xx依赖名称": "xx依赖路径" } }</script> <script type="module"> import xx from 'xx 依赖名称' </script>

<script type="importmap">
{
"imports": {
"B": "./b.js"
}
}
</script>

<script type="module">
import { b } from 'B';
b();
</script>

三、原理


3.1 模块解析

  1. 将引入路径转化为完整的 url 地址

  2. 通过完整的 url 地址,下载对应文件

  3. 解析文件, 寻找所有的静态导入语句, 注意: 静态导入语句一定是在最顶层,而且浏览器也只找顶层。将这些语句放置在文件的最前面。

  4. 将这些静态导入语句分别递归执行前面步骤

  5. 所有模块解析完成后, 就要开始执行啦

3.2 模块执行

从上到下依次执行代码:

  1. 执行到 import xx from "xx 依赖路径 时, 进入 xx 依赖路径, 执行 xx 依赖路径 代码