在 ECMAScript 模块 (ESM) 系统中,符号绑定是指模块导出和导入的变量、函数或类在模块间的连接方式。ESM 使用静态绑定机制,与 CommonJS 的动态绑定有显著区别。
基本符号绑定概念
1. 导出绑定 (Export Bindings)
// module.js
export let count = 0; // 导出变量绑定
export function increment() { count++; } // 导出函数绑定
export class Counter {} // 导出类绑定
2. 导入绑定 (Import Bindings)
// main.js
import { count, increment, Counter } from './module.js';
console.log(count); // 0
increment();
console.log(count); // 1 - 绑定是实时的
ESM 绑定的关键特性
1. 实时绑定 (Live Bindings)
-
导出模块中的值变化会反映在所有导入模块中
-
适用于
let和var导出的变量 -
对于
const导出,绑定也是实时的,但值不可变
// module.js
export let value = 1;
setTimeout(() => { value = 2 }, 1000);
// importer.js
import { value } from './module.js';
console.log(value); // 初始1,1秒后变为2
2. 不可重新赋值
-
导入的绑定在导入模块中是只读的
-
不能直接修改导入的值
import { count } from './module.js';
count = 10; // TypeError: Assignment to constant variable
3. 静态解析
-
绑定在代码执行前就确定
-
不允许动态导入/导出(顶级作用域)
// 不允许
if (condition) {
import './module.js'; // SyntaxError
}
特殊绑定形式
1. 命名空间绑定
import * as module from './module.js';
console.log(module.count);
2. 默认绑定
// module.js
export default function() { /* ... */ }
// importer.js
import myFunction from './module.js';
3. 重命名绑定
import { count as counter } from './module.js';
export { increment as inc } from './module.js';
与 CommonJS 的区别
| 特性 | ESM | CommonJS |
|---|---|---|
| 绑定时间 | 静态(解析时) | 动态(运行时) |
| 绑定性质 | 实时绑定 | 值拷贝 |
| 循环依赖 | 处理更合理 | 可能部分未初始化 |
| 重新赋值 | 不允许 | 允许 |
循环依赖中的绑定行为
ESM 处理循环依赖更可靠,因为绑定是静态建立的:
// a.js
import { b } from './b.js';
export let a = 'a';
console.log(b); // 即使b.js未完全执行,也能访问b
// b.js
import { a } from './a.js';
export let b = 'b';
console.log(a); // 即使a.js未完全执行,也能访问a
ESM 的符号绑定机制是其模块系统的核心特性之一,提供了更可靠和可预测的模块交互方式。
ESM 中的符号绑定机制解析
1152

被折叠的 条评论
为什么被折叠?



