ESM模块化

60 阅读1分钟

js模块化

一、ESM模块化

(ECMAScript Modules) 的核心知识点:

  1. 基本语法

导出 (Export)

// 命名导出
export const name = 'Vue'
export function hello() {}
export class Component {}

// 默认导出
export default function() {}

// 导出列表
export { name, hello, Component as MyComponent }

导入 (Import)

// 导入命名导出
import { name, hello } from './module.js'

// 导入默认导出
import MyDefault from './module.js'

// 导入所有导出
import * as all from './module.js'

// 动态导入
const module = await import('./module.js')
  1. 导出/导入重命名

// 导出时重命名
export { name as myName }

// 导入时重命名
import { name as myName } from './module.js'
  1. 重新导出

// 重新导出其他模块的所有命名导出
export * from './module.js'

// 选择性重新导出
export { name, hello } from './module.js'

// 重命名后重新导出
export { name as myName } from './module.js'
  1. 特性

  1. 严格模式:默认启用严格模式
  2. 静态分析:支持静态分析,便于 tree-shaking
  3. 异步加载:原生支持动态 import()
  4. 循环依赖:支持循环引用
  5. 只读视图:导入的值是只读的
  1. 与 CommonJS 的主要区别

特性ESMCommonJS
加载方式异步同步
导入导出静态动态
值类型只读的引用值的拷贝
this 指向undefinedexports 对象
文件扩展名必须包含可省略
  1. 在浏览器中使用

<!-- 必须指定 type="module" -->
<script type="module" src="app.js"></script>

<!-- 内联模块 -->
<script type="module">
  import { name } from './module.js'
  console.log(name)
</script>
  1. 在 Node.js 中使用

// package.json
{
  "type": "module"  // 启用 ESM
}
  1. 动态导入

// 返回 Promise
const module = await import('./module.js')

// 动态路径
const path = './' + 'module.js'
const module = await import(path)
  1. 模块元信息

import.meta.url     // 当前模块的 URL
import.meta.resolve // 解析模块说明符
  1. 顶级 await

// 在模块顶层可以直接使用 await
const data = await fetchData()

ESM 是现代 JavaScript 开发中的标准模块系统,Vue 3 也完全采用 ESM 编写,这使得它能够更好地支持 tree-shaking 等优化。