模块系统是 TypeScript 项目组织代码的核心机制,主要用于代码拆分、复用和依赖管理。
TypeScript 支持 ES Modules(ESM) 和 CommonJS 两种主流模块系统,理解它们的差异和使用场景是前端开发中的必备技能。
以下从基础语法、配置、互操作性到实战建议展开说明。
1. 基础语法
ESM 使用 import/export
语法,是 ECMAScript 官方标准,适用于现代浏览器和 Node.js(需配置)。
// math.ts
// 具名导出
export const add = (a: number, b: number): number => a + b;
// 默认导出
export default function subtract(a: number, b: number): number {
return a - b;
}
// app.ts
import { add } from './math.js'; // 导入具名导出(注意编译后路径)
import subtract from './math.js'; // 导入默认导出
console.log(add(1, 2)); // 3
console.log(subtract(5, 3)); // 2
关键点:
.js
),因编译后代码为 JS。1. 基础语法
CommonJS 使用 require/module.exports
,常见于 Node.js 环境。
// math.ts
// 具名导出
exports.add = (a: number, b: number): number => a + b;
// 默认导出(需特殊处理)
export default function subtract(a: number, b: number): number {
return a - b;
}
// app.ts
const math = require('./math'); // 导入整个模块
const { add } = require('./math'); // 解构具名导出
const subtract = require('./math').default; // 导入默认导出(需配置支持)
console.log(add(1, 2)); // 3
console.log(subtract(5, 3)); // 2
关键点:
module.exports
或 exports.default
处理。require
可能导致类型丢失,需配合 TypeScript 类型声明。1. tsconfig.json
核心配置项
module
: 指定编译后的模块系统(如 "ES6"
或 "CommonJS"
)。esModuleInterop
: 允许 ESM 和 CommonJS 的互操作性(建议开启)。allowSyntheticDefaultImports
: 兼容无默认导出的模块。{
"compilerOptions": {
"module": "ES6",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
}
}
1. 在 ESM 中导入 CommonJS 模块
需开启 esModuleInterop
,TypeScript 会自动处理兼容。
// 导入 CommonJS 模块(如 lodash)
import _ from 'lodash'; // 默认导入(esModuleInterop 生效)
import * as lodash from 'lodash'; // 命名空间导入(无 esModuleInterop 时)
2. 在 CommonJS 中导入 ESM 模块
需使用动态 import()
或编译为 CommonJS 格式。
// 动态导入(Node.js 环境)
const math = await import('./math.js');
console.log(math.add(1, 2));
1. 统一模块系统
2. 第三方库兼容性
"type": "module"
。@types/xxx
补充类型。3. 默认导出陷阱
// 错误:默认导出未正确处理
module.exports = { add, subtract };
// 正确:需通过 default 或 esModuleInterop
export default { add, subtract };
4. 路径与扩展名
'./math.js'
),CommonJS 可省略扩展名。5. 循环依赖
TypeScript 的模块系统选择需结合项目环境:
esModuleInterop
实现平滑迁移。核心配置建议:
esModuleInterop
和 allowSyntheticDefaultImports
。通过合理配置和规范使用,可高效管理代码依赖,避免常见的模块陷阱。