概述
JavaScript 有很多处理模块化代码的不同方法。TypeScript 在 2012 年就出现了,已经实现了对很多种格式的支持,但随着时间的推移,社区和 JavaScript 规范已经汇聚成一种称为 ES 模块(或ES6模块)的格式。你可能知道它就是 import/export
语法。
ES 模块是在 2015 年加入 JavaScript 规范的,到2020年,大多数 web 浏览器和 JavaScript 运行时都支持 ES 模块。
手册将涵盖 ES 模块和在它之前流行的 CommonJS 模块 module.export =
语法,你可以在 Modules 下的 reference 部分找到关于其他模块模式的信息。
JavaScript 模块是如何定义的
在 TypeScript 中,就像在 ECMAScript 2015 中一样,任何包含顶级导入或导出的文件都被认为是一个模块。
相反,没有任何顶级导入或导出声明的文件被视为其内容在全局范围内可用的脚本(因此也对模块可用)。
模块在它们自己的作用域中执行,而不是在全局作用域中执行。这意味着在模块中声明的变量、函数、类等在模块外部是不可见的,除非它们被显式导出。相反,要使用从不同模块导出的变量、函数、类、接口等,必须导入它们。
非模块
在我们开始之前,了解 TypeScript 对模块的处理是很重要的。JavaScript 规范声明,任何没有 export
或顶级 await
的 JavaScript 文件都应该被视为脚本,而不是模块。
在脚本文件中,变量和类型声明处在全局共享作用域,并且假设你会使用 -- outFile 编译器选项将多个输入文件连接到一个输出文件中,或是在 HTML 中使用多个 <script>
标记来加载这些文件(以正确的顺序!)。
如果你的文件当前没有任何 import
或 export
,但你希望它被视为模块,则添加该行:
export {};
这将把文件变成一个不导出任何内容的模块。无论你的模块目标是什么,此语法都可以工作。
TypeScript 中的模块
背景阅读:
在 TypeScript 中编写基于模块的代码时,主要需要考虑三件事
- 语法:我想使用什么语法来导入和导出?
- 模块解析:模块名(或路径)和磁盘上的文件之间的关系是什么?
- 模块输出目标:发出的 JavaScript 模块应该是什么样的?
ES Module 语法
文件可以通过 export default
声明默认导出:
// @filename: hello.ts
export default function helloWorld() {
console.log("Hello, world!");
}
然后通过 import 导入:
import hello from "./hello.js";
hello();
除了默认导出之外,你还可以通过忽略 default
从而 export
多个变量和函数:
// @filename: maths.ts
export var pi = 3.14;
export let squareTwo = 1.41;
export const phi = 1.61;
export class RandomNumberGenerator {}
export function absolute(num: number) {
if (num < 0) return num * -1;
return num;
}
这些可以通过 import
语法在另一个文件中使用:
import { pi, phi, absolute } from "./maths.js";
console.log(pi);
const absPhi = absolute(phi);
// ^ = const absPhi: number
额外的 import
语法
导入可以使用 import { old as new }
这样的格式重命名:
import { pi as π } from "./maths.js";
console.log(Ï€);
// ^ = (alias) var π: number
// import π
你可以将上述语法混合并匹配到单个 import
中:
// @filename: maths.ts
export const pi = 3.14;
export default class RandomNumberGenerator {}
// @filename: app.ts
import RNGen, { pi as π } from "./maths.js";
RNGen;
// ^ = (alias) class RNGen
// import RNGen
console.log(Ï€);
// ^ = (alias) const π: 3.14
// import π
你可以使用 * 作为名称,将所有导出的对象放入单个命名空间中:
// @filename: app.ts
import * as math from "./maths.js";
console.log(math.pi);
const positivePhi = math.absolute(math.phi);
// ^ = const positivePhi: number
你可以通过 import "./file
导入一个文件,而不包含任何变量到你当前的模块中:
// @filename: app.ts
import "./maths.js";
console.log("3.14");
在本例中,import
不执行任何操作。然而,matha.ts
中的所有代码会被评估,这可能会引发影响其他对象的副作用。
TypeScript 特有的 ES Module 语法
可以使用与 JavaScript 值相同的语法导出和导入类型:
// @filename: animal.ts
export type Cat = { breed: string; yearOfBirth: number };
export interface Dog {
breeds: string[];
yearOfBirth: number;
}
// @filename: app.ts
import { Cat, Dog } from "./animal.js";
type Animals = Cat | Dog;
TypeScript 用 import type
扩展了 import
语法,import type
是一个只能导入类型的导入。
// @filename: animal.ts
export type Cat = { breed: string; yearOfBirth: number };
// 'createCatName' cannot be used as a value because it was imported using
// 'import type'.
export type Dog = { breeds: string[]; yearOfBirth: number };
export const createCatName = () => "fluffy";
// @filename: valid.ts
import type { Cat, Dog } from "./animal.js";
export type Animals = Cat | Dog;
// @filename: app.ts
import type { createCatName } from "./animal.js";
const name = createCatName();
该语法允许像 Babel、swc 或 esbuild 这样的非 TypeScript 编译器知道哪些导入可以被安全地删除。
带有 CommonJS 行为的 ES 模块语法
TypeScript 的 ES 模块语法直接与 CommonJS 和 AMD 的 require
相关。在大多数情况下,使用 ES 模块的导入与这些环境的 import
是相同的,但这种语法需要确保 TypeScript 文件与 CommonJS 的输出是一对一匹配:
import fs = require("fs");
const code = fs.readFileSync("hello.ts", "utf8");
你可以在 modules reference page 了解更多关于此语法的信息。
CommonJS 语法
CommonJS 是 npm 上大多数模块都使用的格式。即使你正在使用上面的 ES 模块语法编写代码,对 CommonJS 语法的工作原理有一个简要的了解也会有助于调试。
导出
标识符是通过在全局模块 module
上设置 exports
属性导出的。
function absolute(num: number) {
if (num < 0) return num * -1;
return num;
}
module.exports = {
pi: 3.14,
squareTwo: 1.41,
phi: 1.61,
absolute,
};
然后这些文件就可以通过 require 语句导入:
const maths = require("maths");
maths.pi;
// ^ = any
或者,你可以使用 JavaScript 中的解构特性进行一些简化:
const { squareTwo } = require("maths");
squareTwo;
// ^ = const squareTwo: any
CommonJS 和 ES Modules 之间的交互
CommonJS 和 ES 模块之间的特性不匹配,因为ES模块只支持将默认导出作为对象,而不支持将其作为函数。TypeScript 有一个编译器标志来减少两个不同约束集之间的摩擦 esModuleInterop。
TypeScript 的模块解析选项
模块解析是从 import 或 require 语句中获取字符串,并确定该字符串所指向的文件的过程。
TypeScript 包括两种解析策略:Classic 和 Node。Classic,当编译器标志 module 不是 commonjs
时的默认值,包含它是为了向后兼容。Node 策略复制了 Node.js 在 CommonJS 模式下的工作方式,并附加了 .ts
和 .d.ts
检查。
TypeScript 中有很多 TSConfig 标志会影响模块策略:
moduleResolution, baseUrl, paths, rootDirs
关于这些策略如何工作的完整细节,可以参考 Module Resolution。
TypeScript 的模块输出选项
有两个选项会影响所发出的 JavaScript 输出:
- target - 决定了哪些 JS 特性是低层次的(转换为在旧的 JavaScript 运行时运行),哪些是完好无损的
- module - 它决定了哪些代码用于模块之间的交互
你使用何种 target
取决于你希望在 JavaScript 运行时运行 TypeScript 代码的特性。这可能是:你支持的最古老的 web 浏览器,你希望在其上运行的 Node.js 的最低版本,或者可能来自运行时的唯一约束 -- 例如 Electron。
模块之间的所有通信都是通过模块加载器进行的,编译器标志 module 决定使用哪个模块。运行时,模块加载器负责定位和执行某个模块执行前的所有依赖。
例如,下面是一个使用 ES 模块语法的 TypeScript 文件,展示了一些不同的模块选项:
import { valueOfPi } from "./constants.js";
export const twoPi = valueOfPi * 2;
ES2020
import { valueOfPi } from "./constants.js";
export const twoPi = valueOfPi * 2;
CommonJS
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.twoPi = void 0;
const constants_js_1 = require("./constants.js");
exports.twoPi = constants_js_1.valueOfPi * 2;
UMD
(function (factory) {
if (typeof module === "object" && typeof module.exports === "object")
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports", "./constants.js"], factory);
}
})(function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.twoPi = void 0;
const constants_js_1 = require("./constants.js");
exports.twoPi = constants_js_1.valueOfPi * 2;
});
注意,ES2020 实际上与原始的 index.ts 相同。
你看到在 TSConfig Reference for module 中看到所有可用的选项以及它们发出的 JavaScript 代码。
TypeScript 命名空间
TypeScript 有自己的模块格式,叫做 namespaces
,它早于 ES 模块标准。这种语法有很多有用的特性,可以创建复杂的定义文件,并且在 DefinelyTyped 中仍然活跃。虽然没有被弃用,但名称空间中的大多数特性都存在于 ES 模块中,我们建议你使用它与 JavaScript 的方向保持一致。你可以在 the namespaces reference page 了解更多关于名称空间的信息。