TypeScript 模块
模块把代码按文件拆分,文件内的 export 决定对外暴露什么,import 决定引入什么,每个文件都有独立作用域。TypeScript 支持 ES 模块语法(import/export),也可按 tsconfig 的 module 选项编译成 CommonJS、AMD 等格式,是现代项目组织代码的基本单位。
导出与导入
// math.ts —— 导出命名成员
export const PI = 3.14;
export function square(n: number): number {
return n * n;
}
// main.ts —— 按名字导入
import { PI, square } from "./math";
console.log(square(PI)); // 输出:9.8596
console.log(square(4)); // 输出:16
默认导出
每个模块可以有一个 default 导出,导入时名字可自取:
// greeting.ts
export default function hello(name: string): string {
return `你好,${name}`;
}
// main.ts
import hi from "./greeting"; // 默认导入,名字任意
console.log(hi("小明")); // 输出:你好,小明
改名与整体导入
// 局部改名:解决同名冲突
import { square as sq } from "./math";
console.log(sq(5)); // 输出:25
// 整体导入:把模块所有导出收进一个对象
import * as math from "./math";
console.log(math.PI); // 输出:3.14
console.log(math.square(2)); // 输出:4
重导出与类型导入
// 聚合模块:把多个模块的导出"搬运"到当前模块再统一出口
export * from "./math";
export { hello as default } from "./greeting";
// geo.ts
export interface Point {
x: number;
y: number;
}
export const origin: Point = { x: 0, y: 0 };
// 只用 import type 引类型:编译后会被完全擦除,零运行时开销
import type { Point } from "./geo";
import { origin } from "./geo";
const p: Point = { ...origin, x: 1 };
console.log(p); // 输出:{ x: 1, y: 0 }
模块格式与选型
编译结果由 tsconfig.json 的 module 字段决定:
| 选项 | 产物格式 | 适用场景 |
|---|---|---|
| esnext / es2015 | 原生 import/export | 浏览器 + 打包器(Vite、Webpack) |
| commonjs | require / module.exports | Node.js 传统项目 |
| nodenext | 按 Node 的 ESM/CJS 规则 | 现代 Node.js |
{
"compilerOptions": {
"module": "esnext",
"moduleResolution": "bundler"
}
}
小结
模块按文件隔离作用域,export/import 控制边界:命名导出适合工具集,默认导出适合单一入口,import type 只引类型零开销。新代码一律用模块组织代码,命名空间只留给少数全局场景。