export 导出、import 导"> export 导出、import 导"> export 导出、import 导">
TypeScript 词条目录
前端Wiki/TypeScript/深入/模块与声明文件

模块与命名空间

TS 全面采用 ES 模块:export 导出、import 导入,编译时按目标配置降级(ESNext 保留原样;较旧 target 可能降成 CommonJS)。类型也可以导出,且 import type 可以只引入类型不进运行时。

命名空间(namespace)是模块方案诞生前的老办法,用 namespace X {} 包一层再 export.internal。新项目一律用模块;命名空间主要在维护老代码与 .d.ts 全局声明里出现。

  • 编译产物按 module 配置降级:esnext / commonjs / amd
  • import type 只引类型,编译后整行被删除
  • 命名空间是历史方案,新项目一律用 ES 模块
TS
// utils.ts —— 导出
export function add(a: number, b: number) { return a + b; }
export type ID = number | string;

// 使用处
import { add, type ID } from './utils';   // type 修饰:不进运行时
const sum: number = add(1, 2);
const id: ID = 'ts-001';

// 命名空间(老代码才会见到)
namespace Legacy {
  export function old() { return '我是上个时代的组织方式'; }
}
console.log(Legacy.old());
JS
// module 编译成 commonjs 时大概长这样:
Object.defineProperty(exports, '__esModule', { value: true });
exports.add = add;
function add(a, b) { return a + b; }
// import type 的那行整体消失

const sum = add(1, 2);
console.log(sum);        // 3

var Legacy;
(function (Legacy) {
  function old() { return '我是上个时代的组织方式'; }
  Legacy.old = old;
})(Legacy || (Legacy = {}));
console.log(Legacy.old());
本节要点新项目一律用 ES 模块;import type 只引类型、不进产物;命名空间留给老代码。