一、CommonJS与ES对比
分类 | CommonJS | ES |
---|---|---|
加载模式 | 运行时加载,速度较慢 | 编译时加载,速度更快 |
加载方式 | 同步加载 | 异步加载 |
代码实现 | 导入:module.exports ;导入:require
|
导出:export ;导入:import
|
导出内容 | 值的拷贝:内部值发生改变后,外部不能获取到最新值 | 值的引用:内部的值发生改变后,外部可获取到最新的值 |
二、ES的其他特性
1、 使用配置
node.js 环境也是一样的,不能在非 ES 模块的环境下使用 import
和 export
语句,因为对于 .js 文件,node.js 默认会当作 CommonJS
模块,在 CommonJS
模块中使用 ES 模块的语法,当然要报错啦。
可通过如下方式进行配置:
在package.json
文件,并指定 "type": "module"
image.png
2、动态导入
为了提升运行效率,有写模块我们可进行按需导入,即在真实使用的时候,才将该js文件导入到浏览器中。
可使用import()
进行动态导入;
components: {
Product: () => import("./components/Product.vue"),
},
// 可使用Product组件
在vue3中可使用defineAsyncComponent
const Product= defineAsyncComponent(() =>
import("./components/Product.vue")
);
3、编译时执行
ES 模块的设计思想是尽量的静态化,使得编译时就能确定模块的依赖关系,以及输入和输出的变量。因此不能使用表达式、变量和条件语句(这些只有在运行时才能得到结果的语法结构)。
// 报错
if (type === 1) {
import { add } from './add.js';
} else {
import { minus } from './minus.js';
}
三、script模块引入
使用script模块引入的使用,通过属性可以设置引入的方式;
分类 | 实现 | 描述 |
---|---|---|
普通script标签 | <script> |
同步加载脚本,加载后立即执行 |
defer 属性 |
<script defer > |
异步加载脚本,等待浏览器渲染完成后,才执行脚本 |
async 属性 |
<script async> |
异步加载脚本,加载后才执行脚本 |
type="module" |
<script type="module"> |
与defer 一样 |
module +async
|
<script type="module" async> |
异步加载脚本,加载后才执行脚本 |