# 23 · ESM：活绑定、`import type` 与模块语义

> 学完这章，你能说清 `import` 为什么是静态结构、活绑定与快照的差别，并用 `import type` 把类型与运行时代码彻底分开。

## 本章目标

- [ ] 能写出静态 `import`/`export`，并解释「提升到顶部」与「不能条件化」
- [ ] 能证明 ESM 是活绑定，并说明它和 CJS 快照的差别
- [ ] 能解释模块顶层 `this` 为什么是 `undefined`、模块为什么只求值一次
- [ ] 能用动态 `import()` 做按需加载，并处理失败
- [ ] 能用 `import type` / `export type` 配合 `verbatimModuleSyntax`，并读懂 `TS1484` / `TS1205`

## 前置知识

- 第 21 章（CJS 快照）、第 22 章（UMD/SystemJS）
- 第 13 章（声明文件）

## 约束 → 方案 → 新问题

| 上一个方案的约束 | 本方案解决什么 | 引入的新问题 |
| --- | --- | --- |
| CJS 同步加载、浏览器不可用 | ESM 静态声明依赖，加载器异步取文件 | 浏览器必须支持 ESM；老环境要转译 |
| CJS 导出是对象属性，可能变快照 | 活绑定让导入方看到变量本身 | 绑定只读，不能从导入方赋值 |
| 全局/AMD 无法静态分析 | `import` 是静态结构，可 tree-shaking | 默认导出与副作用让分析变复杂 |
| 运行时才能确定依赖 | 动态 `import()` 按需加载 | 路径必须可分析，错误处理要自己做 |
| 类型与值混在一个导入里 | `import type` / `export type` | 配置不对会报 `TS1484`/`TS1205` |

时间线片段：

```text
2015 ── ES2015 引入 ESM 语法
2017 ── 浏览器开始支持 <script type="module">
2018 ── Node ESM 实验
2020 ── 打包器普遍以 ESM 为输入
2023 ── TS 5.0 verbatimModuleSyntax
2025 ── TS 5.9 import defer（浏览器支持有限）
```

## 从你熟悉的语言出发

| 你熟悉的 | 导入的语义 | TypeScript 的对应 | 关键差异 |
| --- | --- | --- | --- |
| Java `import` | 编译期符号引用，运行时类加载 | ESM `import` | Java 的 import 不加载类；ESM 的 import 触发模块加载 |
| C `#include` | 文本包含，编译期展开 | ESM | ESM 是模块实例绑定，不是文本替换 |
| Go `import` | 包级初始化，编译器排序 | ESM | ESM 的绑定是活的，Go 的包变量也是共享但初始化顺序不同 |
| Python `import` | 模块对象缓存 | ESM | Python 导入模块对象；ESM 导入绑定，且只读 |

一句话：**ESM 的 `import` 既是编译期依赖声明，也是运行时加载指令。**

## 正文

### 23.1 静态结构：只能在顶层

```ts
import { area } from './types.js';
import type { Shape } from './types.js';

export const name = 'demo';
export { area };
```

三条硬规则：

1. `import`/`export` 必须在模块顶层，不能放进 `if`、函数、`try`。
2. 声明会被提升：无论写在文件哪一行，依赖都先解析。
3. 路径必须是字符串字面量；不能用变量拼。

需要条件加载时，用动态 `import()`：

```ts
const module = await import('./lazy.js');
```

### 23.2 活绑定

```ts
// counter.ts
export let count = 0;
export function increment(): void {
  count += 1;
}
```

```ts
// main.ts
import { count, increment } from './counter.js';
count; // 0
increment();
count; // 1
```

导入的是**绑定**，不是值拷贝。产物里也保留 `import { count, increment }`，没有 `const count = ...`。

约束：导入绑定是只读的。`count = 1` 在导入方会报错；只能由导出方修改。

### 23.3 模块只求值一次

```ts
// side-effect.ts
export let evaluations = 0;
evaluations += 1;
```

无论多少个模块 import 它，`evaluations` 都只加一次。模块图保证「每个模块实例只求值一次」，这是 ESM 的单例语义。

这与 CJS 的缓存类似，但 ESM 的保证来自规范与加载器，不依赖 `require` 实现。

### 23.4 顶层 `this` 与严格模式

ES 模块自动严格模式，顶层 `this` 是 `undefined`：

```ts
export const topThis = this; // undefined
```

classic 脚本顶层 `this` 是全局对象。这是判断「脚本 vs 模块」的运行时特征之一（另一个是 `import.meta`）。

类型层对顶层 `this` 的建模并不可靠（可能被当成全局对象或 `any`），所以不要用类型去推断它的值。

### 23.5 `import type` 与 `verbatimModuleSyntax`

```ts
import { area } from './types.js';
import type { Shape } from './types.js';
```

- `import { area }`：值导入，产物保留。
- `import type { Shape }`：类型导入，产物完全擦除。

基线的 `verbatimModuleSyntax: true` 要求显式区分。写错会报：

```text
demo/type-reexport.ts(1,10): error TS1484: 'Shape' is a type and must be imported using a type-only import when 'verbatimModuleSyntax' is enabled.
demo/type-reexport.ts(3,10): error TS1205: Re-exporting a type when 'verbatimModuleSyntax' is enabled requires using 'export type'.
```

修复：

```ts
import type { Shape } from './types.js';
export type { Shape };
```

`isolatedModules` 也要求同样的写法，因为单文件转译器无法判断一个名字是类型还是值。

### 23.6 `export *` 的冲突

```ts
export * from './a.js';
export * from './b.js';
```

如果两个模块都导出 `shared`，TS 报：

```text
demo/ambiguous.ts(4,1): error TS2308: Module '../src/a.js' has already exported a member named 'shared'. Consider explicitly re-exporting to resolve the ambiguity.
```

修复：显式选择。

```ts
export { onlyA, shared } from './a.js';
export { onlyB } from './b.js';
```

ESM 规范本身对歧义 star 导出的处理是「省略该名字」；TS 选择报错，避免静默丢导出。

### 23.7 动态 `import()` 与 `import defer`

```ts
const module = await import('./lazy.js');
module.value();
```

动态 import：

- 返回 `Promise<ModuleNamespace>`。
- 可以放在任何位置（条件、事件回调）。
- 打包器会把它拆成独立 chunk（第 17 章 JS 教程的 code splitting）。

TS 5.9 引入 `import defer`：

```ts
import defer * as ns from './heavy.js';
```

它延迟模块求值到第一次访问，但语法支持有限（需要 `module: "esnext"` 或 `"preserve"`；浏览器原生支持仍很少）。本章不把它放进可运行示例，只作为版本敏感特性记录。

## 类型错误现场

**场景一：类型导入未加 `type`**。`examples/23-esm-live-bindings/04-import-type/demo/type-reexport.ts`：

```ts
import { Shape } from '../src/types.js';
export { Shape };
```

真实报错（TypeScript 7.0.2）：

```text
demo/type-reexport.ts(1,10): error TS1484: 'Shape' is a type and must be imported using a type-only import when 'verbatimModuleSyntax' is enabled.
demo/type-reexport.ts(3,10): error TS1205: Re-exporting a type when 'verbatimModuleSyntax' is enabled requires using 'export type'.
```

- `TS1484`：值导入位置引入了类型。
- `TS1205`：重导出类型时没写 `export type`。
- 修复：`import type { Shape }` + `export type { Shape }`。

**场景二：star 导出冲突**。`examples/23-esm-live-bindings/05-export-star/demo/ambiguous.ts`：

```text
demo/ambiguous.ts(4,1): error TS2308: Module '../src/a.js' has already exported a member named 'shared'. Consider explicitly re-exporting to resolve the ambiguity.
```

- `TS2308`：两个 `export *` 提供了同名成员。
- 修复：显式 `export { shared } from './a.js'`，或改名。

## 反直觉差异：活绑定不是「引用对象」

**你的直觉**：ESM 的 `import { count }` 和 CJS 的 `require().count` 差不多，只是语法不同；既然都是对象属性，应该都能改。

**实际行为**：ESM 导入的是绑定本身，不是对象属性，也不能赋值：

```ts
import { count } from './counter.js';
count = 1; // error：Cannot assign to 'count' because it is an import
```

而且绑定的「活」体现在导出方的变量变化上：

```ts
// 导出方
export let count = 0;
setTimeout(() => { count = 1; }, 0);

// 导入方
import { count } from './counter.js';
// 之后的某个时刻，count 会变成 1
```

CJS 要模拟这个效果，必须导出 getter 或函数。

**为什么这样设计**：ESM 在规范层把导入建模为「模块环境记录中的间接绑定」，这样打包器可以做静态分析、循环依赖有确定的 TDZ 行为、tree-shaking 也能判断哪些绑定被使用。CJS 的对象属性模型更灵活，但没有这些保证。

**正确写法**：

- 不要在导入方修改导入的绑定；需要可变状态就导出对象/方法。
- 循环依赖里注意 TDZ：访问还没初始化的 `let`/`const` 会抛 `ReferenceError`（第 24 章）。
- 需要「快照」语义时，显式复制：`const snapshot = count;`。

## 示例索引

| 目录 | 演示什么 | 预期看到 |
| --- | --- | --- |
| `examples/23-esm-live-bindings/01-live-bindings/` | 活绑定 | `before:0`、`after:1` |
| `examples/23-esm-live-bindings/02-top-level-this/` | 顶层 `this` | `topThis:undefined` |
| `examples/23-esm-live-bindings/03-dynamic-import/` | 动态 `import()` | `lazy-loaded` |
| `examples/23-esm-live-bindings/04-import-type/` | `import type` 擦除 | `rect:6`；失败配置贴 `TS1484`/`TS1205` |
| `examples/23-esm-live-bindings/05-export-star/` | star 冲突与单次求值 | `1:2:a`、`evaluations:1`；失败配置贴 `TS2308` |

## 练习题

1. 写一个模块，导出 `let current` 与 `setCurrent()`，在另一个模块里观察活绑定；再用 `const snapshot = current` 对比。
2. 把 `examples/23-esm-live-bindings/03-dynamic-import/src/main.ts` 改成「加载失败时回退」，用一个不存在的路径触发 `catch`。
3. 给 `examples/23-esm-live-bindings/05-export-star/src/barrel.ts` 增加 `export type` 的重导出，验证 `verbatimModuleSyntax` 下仍然合法。

<details><summary>参考答案</summary>

1. 导出方 `export let current = 'a'; export function setCurrent(v: string) { current = v; }`；导入方 `setCurrent('b')` 后 `current` 变成 `'b'`；`snapshot` 仍是 `'a'`。
2. ```ts
   try {
     const mod = await import('./missing.js');
     return [mod.value()];
   } catch (error) {
     return [`fallback:${error instanceof Error ? error.name : 'unknown'}`];
   }
   ```
   动态 import 失败会 reject，错误类型取决于加载器（通常是 `TypeError`）。
3. `export type { Shape } from './types.js';` 合法；若写成 `export { Shape }` 会报 `TS1205`。

</details>

## 章末自检

1. `import` 为什么不能放在 `if` 里？
2. 活绑定与 CJS 快照的差别是什么？
3. 模块为什么只求值一次？
4. 模块顶层 `this` 是什么？
5. `import type` 与 `verbatimModuleSyntax` 的关系？
6. `export *` 冲突时 TS 报什么？

<details><summary>参考答案</summary>

1. 它是静态结构，加载器在求值前就要解析依赖图；条件加载用动态 `import()`。
2. 活绑定指向导出方变量本身；CJS 导出对象属性，赋值即快照。
3. 模块图保证每个模块实例只求值一次。
4. `undefined`（模块自动严格模式）。
5. `verbatimModuleSyntax` 要求类型导入必须写 `import type`，否则报 `TS1484`。
6. `TS2308`，提示显式重导出解决歧义。

</details>

## 延伸阅读

- ECMA-262 §16.2 *Modules*（Module Records、Live Bindings）
- TypeScript Handbook：*Modules*、*Module Resolution*
- TypeScript 5.0 Release Notes：*`verbatimModuleSyntax`*
- TypeScript 5.9 Release Notes：*`import defer`*
- JavaScript 教程 `../javascript/docs/13-esm.md`（运行时与加载语义）
