第十二章讲的是 namespace(命名空间);现代项目里组织代码用的是 ES 模块,也就是下面这套 export / import 语法。import { useEffect, useState } from "react"; 这句就属于这里:从包里按名字取出两个导出值。

1. 导出(export)

// 命名导出:一个文件可以有多个
export const PI = 3.14;
export function add(a: number, b: number): number { return a + b; }
export class User {
  constructor(public name: string) {}
}
export interface Point { x: number; y: number; }   // 类型也能导出
 
// 也可以先定义、后集中导出
const version = "1.0.0";
interface Config { debug: boolean; }
export { version, Config };
export { version as appVersion };   // 重命名导出
 
// 默认导出:一个模块只能有一个
export default class Logger {}
// 或者
export default function main() {}
 
// 只导出类型(编译后不产生任何代码)
export type { Point };

2. 导入(import)

import { PI, add } from "./math";            // 命名导入(花括号,名字必须对得上)
import { add as plus } from "./math";        // 重命名导入
import Logger from "./logger";               // 默认导入(不加花括号,名字随便起)
import Logger, { PI } from "./logger";       // 默认 + 命名 混合
import * as math from "./math";              // 整体导入:math.PI、math.add()
import "./polyfill";                         // 只为执行副作用,不导入任何绑定
import { useState, useEffect } from "react"; // 从 npm 包导入(不带 ./ 的是包名)

TypeScript 专有:类型导入

import type { Point, Config } from "./types";       // 只导入类型,编译后被完全擦除
import { type Point, add } from "./types";          // 内联 type 修饰符,按需标注

动态导入(返回 Promise,常用于按需加载 / 代码分割)

const { default: Logger } = await import("./logger");
const math = await import("./math");

3. 重新导出(转发)

// index.ts 里做“统一出口”很常见
export { add } from "./math";
export { add as plus } from "./math";
export * from "./math";
export * as math from "./math";
export type { Point } from "./types";

4. 与 CommonJS 的关系

Node 老项目用的是 CommonJS,写法不同,不要和 import/export 混在同一个文件里:

// CommonJS
const fs = require("fs");
module.exports = { add };
 
// 在 TypeScript 中使用 CommonJS 模块(配合 "module": "commonjs")
import fs = require("fs");
export = myModule;

5. 为什么有的导入带花括号?

花括号不是可选的写法,它直接对应被导入模块是怎么导出的:默认导出(export default)用不带花括号的写法,命名导出(export const / function / class)用带花括号的写法。

// module-a.ts —— 两种导出都有
export default function handler() {}   // 默认导出:一个模块只能有一个
export const PI = 3.14;                // 命名导出
export function add(a: number, b: number) { return a + b; }
 
// main.ts —— 三种导入方式
import handler from "./module-a";                  // 默认导出:名字自己起,不能加花括号
import { PI, add } from "./module-a";              // 命名导出:名字必须和导出时一模一样
import handler2, { PI as pi } from "./module-a";   // 两个都要:默认在前,花括号在后
import * as a from "./module-a";                   // 整体导入:a.PI、a.add()、a.default

对照表:

写法 取的是什么 对应模块里的写法
import fs from “node:fs” 默认导出,本地名字随便起 export default …
import { x } from “./m” 名为 x 的命名导出 export const x / export function x
import { x as y } from “./m” 命名导出 x,在本地叫 y 同上
import * as ns from “./m” 整个模块对象(含 ns.default) 无所谓,命名导出都挂在 ns 上
import “./m” 不导入任何绑定,只执行副作用 通常不关心导出
import type { T } from “./m” 只导入类型,编译后被擦除 export type / interface

那import fs from “node:fs” 为什么也能用? 因为 fs、path、crypto 这些都是 Node 内置模块,底层是 CommonJS。Node 做了兼容:整个 module.exports 被当成默认导出,所以不带花括号就能拿到完整对象。TypeScript 这边的对应开关是 esModuleInterop(配合 allowSyntheticDefaultImports),打开后这种默认导入才不报错。

“整体导入”和“只导入局部”的区别,实际影响:

  • 可读性:import { fileURLToPath } from “node:url” 一眼能看出这个文件只用了这一个 API。
  • 打包体积:带花括号的命名导入,Vite / webpack / rollup 能做 tree-shaking,把没用到的导出裁掉;import * as ns 或默认导入一个整对象,往往整个模块都会被保留。这也是很多库推荐命名导出的原因。
  • 名字绑定:命名导入的名字必须和导出时一致(可用 as 改名);默认导入的名字由你自己定。

记忆口诀:

  • 整个对象一起拿 → 不带花括号(export default)
  • 按名字挑几样 → 带花括号(export const / function / class)
  • 全都要 → import * as ns
  • 不确定 → 先 import * as ns 取回来,再 ns. 点一下,编辑器会列出所有可用名字

6. 默认导出只能有一个吗?

是的,一个模块最多只能有一个默认导出。 道理很简单:默认导出本质上就是名为 default 的一个普通导出名,而同一个导出名在一个模块里不能重复声明。

// ✅ 合法:1 个默认导出 + 任意多个命名导出
export default class Logger {}
export const VERSION = "1.0.0";
export function log(msg: string) { console.log(msg); }
 
// ❌ 解析阶段就报错:Duplicate export of 'default'
export default class A {}
export default class B {}

报错信息长这样(Node、浏览器原生 ESM、Vite 都会报同样的错):

SyntaxError: Duplicate export of 'default'

下面这些写法其实都是在做“默认导出”,彼此冲突:

写法 是不是默认导出
export default function f() {} ✅ 是
export default class C {} ✅ 是
export default { a: 1 } ✅ 是(默认导出一个对象字面量)
export default 42 ✅ 是(可以是任意表达式的值)
export { f as default } ✅ 是,等价写法
export const f = 1 ❌ 不是,是命名导出 f

所以下面这种混用会报错,是很常见的坑:

// ❌ 两种默认导出的写法混用
export default function main() {}
export { helper as default };     // Duplicate export of 'default'

几个容易搞混的细节:

  • import X from “m” 完全等价于 import { default as X } from “m”。也就是说默认导出不是什么特殊机制,只是名字固定叫 default 的命名导出,导入时可以省掉花括号、随便改名。
  • export default function foo() {} 里的名字 foo 只在模块内部可见,对外一律叫 default;别人写 import bar from “m” 拿到的名字就是 bar。别指望导入方能用 foo。
  • 匿名默认导出合法且常见:export default function () {}、export default class {} 都行;但报错堆栈里会显示成 default,不利于排查,所以建议起个名字。
  • export default 后跟表达式时导出的是“值快照”:let n = 1; export default n; 之后再改 n,外部拿到的仍然是 1。想要“活的绑定”,得用 export { n as default }(但不能和上面的 export default 同时出现)。
  • CommonJS 没有“默认导出”这个概念,module.exports 整体被 Node 当成默认导出,这正是上一节 import fs from “node:fs” 能成立的原因。
  • 类型也能默认导出:export default interface User {};开启 –verbatimModuleSyntax 后导入要写成 import type User from “./types”。

实践建议: 库通常优先用命名导出(便于 tree-shaking、改名、自动补全),只有“一个模块就一个主功能”时才用默认导出(例如组件文件 export default MyComponent)。两者混用没问题,但一个模块里绝不能出现两个默认导出。

7. node: 前缀是什么?怎么查看 node:path 的源码?

为什么要写node:

  • 明确表示“这是 Node 内置模块”,不会去 node_modules 里找同名包。历史上有人抢注 fs、path 一类的 npm 包来劫持导入,写 node: 可以彻底避免这种歧义。
  • Node 14.18 / 16 起支持,新代码推荐统一加上。不带前缀的 “path” 仍然能用,只是语义没那么明确。
  • 注意:node: 只能用于内置模块,第三方 npm 包不能这么写。

看“怎么用”最快:类型声明文件

npm i -D @types/node      # 安装 Node 的类型声明

然后编辑器里 Ctrl + 点击(macOS:Cmd + 点击)path 或 fs,会跳到 node_modules/@types/node/path.d.ts。里面是每个函数的签名和注释,查接口最方便。

看“怎么实现”:内置模块的 JS 源码不在本机 node_modules 里

Node 把内置模块的 JS 实现编译进了二进制(内置快照),所以本地找不到 lib/path.js。可行的办法:

# 1) 列出所有内置模块名
node -p "require('node:module').builtinModules.join('\n')"
 
# 2) 看 path 模块导出了哪些东西(只有名字,没有实现)
node -p "Object.keys(require('node:path')).join('\n')"
 
# 3) 旧版本 Node 能打印内置模块的源码字符串;新版本已弃用,可能报错
node -e "console.log(process.binding('natives')['path'])"

最可靠的是直接对照官方仓库:

回到本节开头那段代码:

import fs from 'node:fs';                  // 内置模块整体:fs.readFileSync(...)
import path from 'node:path';              // 整体:path.join(...)
import crypto from 'node:crypto';          // 整体:crypto.randomUUID(...)
import zlib from 'node:zlib';              // 整体:zlib.gzipSync(...)
import { fileURLToPath } from 'node:url';  // 只取 url 模块里的一个命名导出

前四个是把模块整体拿进来(拿到的是带各种方法的对象),最后一个是从 url 模块里按名字挑一个函数,所以带花括号。

8. 注意事项

  • import / export 必须写在模块顶层,不能放进函数或 if 里(import() 动态导入除外)。
  • import 会被提升,语句写在哪不影响执行顺序,但习惯上统一放文件顶部。
  • 文件里只要有顶层 import 或 export,它就是模块,变量不再污染全局。
  • 路径带扩展名的场合:浏览器原生 ESM、Node 的 "type": "module"(ESM 要求写 ./math.js);被 webpack / Vite 打包时通常可以省略。
  • 相关编译选项:module(输出 commonjs / esnext…)、esModuleInterop(默认导入的兼容处理)、verbatimModuleSyntax(开启后类型必须用 import type)。
  • 默认导出和命名导出可以同时用,但一个模块只能有一个默认导出。

9. 练习题

练习 1

把下面这个文件改写成「既提供命名导出、又提供默认导出」的模块,并在另一个文件里用三种方式导入(命名、默认、整体)。

function formatDate(date: Date): string {
  return date.toISOString().split("T")[0];
}
 
class Formatter {
  constructor(public locale: string) {}
  format(date: Date): string {
    return formatDate(date);
  }
}

参考答案

// utils/formatter.ts
export function formatDate(date: Date): string {
  return date.toISOString().split("T")[0];
}
 
export class Formatter {
  constructor(public locale: string) {}
  format(date: Date): string {
    return formatDate(date);
  }
}
 
export default formatDate;   // 默认导出同一个函数
 
// main.ts
import formatDate, { formatDate as named, Formatter } from "./utils/formatter";
import * as formatter from "./utils/formatter";
 
console.log(formatDate(new Date()));
console.log(named(new Date()));
console.log(formatter.formatDate(new Date()));
console.log(new Formatter("zh-CN").format(new Date()));

练习 2

把 types.ts 拆成两个文件:types/point.ts 与 types/user.ts,再用 types/index.ts 统一重新导出,使外部可以直接 import { Point, User } from "./types"。

参考答案

// types/point.ts
export interface Point { x: number; y: number; }
 
// types/user.ts
export interface User { id: string; name: string; }
 
// types/index.ts
export type { Point } from "./point";
export type { User } from "./user";
# ES 模块 import / export

## 导出
### 命名导出
- `export const / function / class`
- 一个文件可以有多个
### 默认导出
- `export default ...`
- 一个模块只能有一个
- 对外名字固定是 `default`
- `import X from "m"` ≡ `import { default as X } from "m"`
- 重复声明报 `Duplicate export of 'default'`
- `export { f as default }` 也算默认导出
### 类型导出
- `export type { Point }`

## 导入
### 不带花括号 `import X from`
- 取默认导出
- 名字自己起
### 带花括号 `import { a, b } from`
- 取命名导出
- 名字必须与导出一致
- 可 `as` 改名
- 利于 tree-shaking
### `import * as ns`
- 整体命名空间
- `ns.a`、`ns.default`
### `import "./x"`
- 只执行副作用
### `import type { T }`
- 只导入类型,编译后擦除
### 动态导入
- `await import("./x")`
- 按需加载 / 代码分割

## 内置模块的兼容
### Node 内置模块底层是 CommonJS
### `module.exports` 被当成默认导出
### TS 开关 `esModuleInterop`
### 所以 `import fs from "node:fs"` 可用

## node: 前缀
### 明确指向内置模块
### 不会去 node_modules 找同名包
### Node 14.18 / 16 起支持
### 只能用于内置模块

## 查看 node:path
### 看接口
- 装 `@types/node`
- Ctrl+点击 → `@types/node/path.d.ts`
### 看实现
- GitHub `nodejs/node` 的 `lib/path.js`
- `fs`/`crypto`/`zlib` 是 C++ 包装,实现看 `src/`
### 列模块名
- `node -p "require('node:module').builtinModules"`

该主题尚不存在

您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。

  • typescript/导入模块.txt
  • 最后更改: 2026/10/10 23:25
  • 由 张叶安