以下是 EMAScript 6(ES6)模块规范的核心要点及细节解析:
导出(export
)
export const a = 1;
export function b() { /* ... */ }
// 或集中导出
const c = 2, d = 3;
export { c, d as renamedD }; // `as` 支持重命名
export default
。export default function() { /* ... */ } // 导出匿名函数
// 或导出声明的值
const obj = {};
export default obj;
export const x = 10;
export default class MyClass { /* ... */ }
导入(import
)
import { a, b } from './module.js';
import { renamedD as d } from './module.js'; // 重命名导入
import MyDefault from './module.js';
import MyDefault, { x } from './module.js';
import * as utils from './math.js';
utils.capitalize('text'); // 调用导出函数
静态化
import
/export
必须位于模块顶层,不可动态嵌套。作用域隔离
动态导入(import()
)
import('./module.js').then(module => {
module.doSomething();
});
模块继承
export * from 'parent'
继承父模块所有命名导出。特性 | ES6 模块 | CommonJS |
---|---|---|
加载方式 | 编译时静态解析 | 运行时动态加载 |
导出类型 | 值引用(实时绑定) | 值拷贝(导出后修改不影响) |
异步支持 | 原生支持动态导入(import() ) |
无原生异步加载 |
顶层作用域 | 严格模式强制启用 | 非严格模式可选 |
循环依赖处理 | 通过实时绑定解决 | 可能因缓存导致不一致 |
resolve.alias
简化路径。示例:混合导出与导入
// math.js export const PI = 3.14; export default function add(a, b) { return a + b; } // app.js import calculate, { PI } from './math.js'; console.log(calculate(1, 2), PI); // 输出:3, 3.14
ES6 模块规范通过静态化、作用域隔离和原生异步支持,提供了标准化、高性能的模块化方案,成为现代前端工程的基石。