模块 in TypeScript
组织 code 使用 ES 模块: 导入, 导出, 默认导出, and re-导出.
你将学到
- 如何导出 and 导入工作 in TypeScript 模块
- 默认导出对比 named 导出
- Re-exporting and barrel files (索引.ts)
- 类型-仅导入 and 导出使用类型 keyword
概念讲解
ES Module Syntax
TypeScript uses the standard ES module system. You export with 导出 and import with 导入. Named exports allow multiple exports per file: 导出 函数 添加() and 导出 const PI. You import them by name: 导入 { 添加, PI } 从 "./math". Every .ts file is a module — its top-level declarations are local unless exported. This encapsulation prevents global namespace pollution.
Default Exports
A default export is the single "主要" export of a module: 导出 默认 类 用户 {}. You import it without braces and can rename it freely: 导入 MyUser 从 "./用户". Default exports are convenient but can make refactoring harder because the import name is arbitrary. Many style guides recommend preferring named exports for consistency and better IDE support (auto-import, find references).
Type-Only Imports
When you import only types (which are erased at compile time), use 导入 类型: 导入 类型 { 用户 } 从 "./类型". This tells the compiler the import is purely a type and should not appear in the compiled JavaScript. This avoids importing runtime code that is only needed for types, which can cause circular dependency issues or unnecessary bundle size. You can also inline it: 导入 { 类型 用户, addUser } 从 "./用户".
示例代码
// --- math.ts ---
export const PI = 3.14159;
export function add(a: number, b: number): number {
return a + b;
}
export default function multiply(a: number, b: number): number {
return a * b;
}
// --- types.ts ---
export interface User {
id: number;
name: string;
}
// --- main.ts ---
import multiply, { add, PI } from "./math";
import type { User } from "./types";
// Re-export (barrel file pattern).
// export * from "./math";
// export * from "./types";
const user: User = { id: 1, name: "Alice" };
console.log(add(2, 3), multiply(4, 5), PI, user.name);
Named 导出允许多个每 file; 默认导出是 单个主要导出. Use 导入类型 for 类型-仅导入到 keep 它们 out 的 compiled 输出. Barrel files (索引.ts) re-导出从 多个模块.
动手试一试
- Code Minifier
Minification 移除 unused 导出 — see 如何模块树-shaking 工作.
- Code Diff
Compare 模块-based code 使用它的 compiled JavaScript 输出.
常见错误
错误写法
Mixing 默认 and named 导出从 相同模块 inconsistently
正确做法
选择 one 样式每 模块 and stick 使用它. Named 导出是 通常 preferred for better refactoring support and explicit 导入 names.
错误写法
Importing 类型不使用 '导入类型' causing circular dependency 错误
正确做法
Use '导入类型 { X }' for 类型-仅导入. 这个 ensures 导入是 erased at 编译时间, breaking circular dependencies 那个 exist 仅 at 类型 level.
练习 模块 in TypeScript
2 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。