Skip to content

模块 ​

JavaScript 有着悠久的历史,有处理模块化代码的不同方式。 自 2012 年以来,TypeScript 已经实现了对许多这些格式的支持,但随着时间的推移,社区和 JavaScript 规范已经融合到一种称为 ES 模块(或 ES6 模块)的格式上。您可能将其称为 / 语法。import``export

ES 模块于 2015 年添加到 JavaScript 规范中,到 2020 年,它在大多数 Web 浏览器和 JavaScript 运行时中得到了广泛的支持。

为了重点讨论,该手册将涵盖 ES 模块及其流行的前体 CommonJS 语法,您可以在模块下的参考部分找到有关其他模块模式的信息。module.exports =

如何定义JavaScript模块 ​

在TypeScript中,就像在 ECMAScript 2015 中一样,任何包含顶级或模块的文件都被视为模块。import export

相反,没有任何顶级导入或导出声明的文件被视为其内容在全局范围内可用的脚本(因此也可用于模块)。

模块在其自己的范围内执行,而不是在全局范围内执行。这意味着在模块中声明的变量、函数、类型等在模块外部不可见,除非使用其中一个导出表单显式导出它们。相反,要使用从不同模块导出的变量、函数、类、接口等,必须使用导入表单之一导入它。

非模块 ​

在我们开始之前,了解 TypeScript 认为模块是什么很重要。JavaScript 规范声明任何没有声明或顶级的 JavaScript 文件都应被视为脚本而不是模块。 import export await

在脚本文件中,变量和类型被声明为在共享全局范围内,并且假定您将使用 outFile 编译器选项将多个输入文件合并到一个输出文件中,或者在 HTML 中使用多个标记来加载这些文件(按正确的顺序!) <script>

如果你有一个当前没有任何 s 或 s 的文件,但你希望被视为一个模块,请添加以下行: import export

ts
export {};

这会将文件理性为不导出任何内容的模块。无论模块目标如何,此语法都有效。

TypeScript中的模块 ​

在TypeScript中编写基于模块的代码时,需要考虑三个主要事项:

  • 语法:我想使用什么语法来导入和导出内容?
  • 模块解析:模块名称(或路径)和磁盘上的文件之间有什么关系?
  • 模块输出目标:我发出的 JavaScript 模块应该是什么样子?

ES 模块语法 ​

可以通过以下方式声明导出:export default

ts
// @filename: hello.ts
export default function helloWorld() {
  console.log("Hello, world!")
}

然后通过以下方式导入:

ts
import helloWorld from "./hello.js";
helloWorld();

除了默认导出之外,您还可以通过省略以下方式导出多个变量和函数:export default

ts
// @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

ts
import {pi, phi, absoluate} from "./maths.js"

console.log(pi);
const absPhi = absoluate(phi);

重新导出 ​

我们经常会去扩展其它模块,并且只导出那个模块的部分内容。 重新导出功能并不会在当前模块导入那个模块或定义一个新的局部变量。

ParseIntBasedZipCodeValidator.ts ​
ts
export class ParseIntBasedZipCodeValidator {
    isAcceptable(s: string) {
        return s.length === 5 && parseInt(s).toString() === s;
    }
}

// 导出原先的验证器但做了重命名
export {ZipCodeValidator as RegExpBasedZipCodeValidator} from "./ZipCodeValidator";

或者一个模块可以包裹多个模块,并把他们导出的内容联合在一起通过语法:export * from "module"。

AllValidators.ts ​
ts
export * from "./StringValidator"; // exports interface StringValidator
export * from "./LettersOnlyValidator"; // exports class LettersOnlyValidator
export * from "./ZipCodeValidator";  // exports class ZipCodeValidator

附加导入语法 ​

可以使用如下格式重命名导入:import {old as new}

ts
import {pi as π} from "./maths.js";
console.log(π);

您可以将上述语法混合并匹配为一个:import

ts
export const pi = 3.14
export default class RandomNumberGenerator{}
ts
import RandomNumberGenerator, {pi as π} from "./maths.js"

RandomNumberGenerator;

console.log(π)

你可以使用以下命令将所有导出的对象放入单个命名空间中:* as name

ts
import * as math from "./maths.js"

console.log(math.pi)

const positivePhi = math.absolute(math.phi)

你可以通过以下方式导入文件而不将任何变量包含到当前模块中:import "./file"

ts
import "./maths.js"

console.log("3.14")

在这种情况下,不执行任何操作。然而,其中的所有代码都经过评估,这可能会触发影响其他对象的副作用。import maths.ts

TypeScript特定的ES模块语法 ​

可以使用与JavaScript值相同的语法导出和导入类型:

ts
export type Cat = { breed: string; yearOfBirth: number }

export interface Dog {
  breeds: string[];
  yearOfBirth: number;
}
ts
import { Cat, Dog } from "./animal.js";
type Animals = Cat | Dog;

TypeScript通过两个概念扩展了语法,用于声明类型的导入:import

import type ​

这是一个只能导入类型的import语句:

ts
export type Cat = {breed: string; yearOfBirth: number};
export type Dog = { breeds: string[]; yearOfBirth: number};
export const createCatName = () => "fluffy";
ts
import type {Cat, Dog} from "./animal.js"
export type Animals = Cat | Dog;
ts
import type {createCatName} from "./animal.js";
const name = createCatName();
// "createCatName" 是使用 "import type" 导入的,因此不能用作值。

lnline imports 内联导入type ​

TypeScript 4.5 还允许单个导入添加前缀,以所求导入的引用是一种类型:type

ts
import { createCatName, type Cat, type Dog} from "./animal"

export type Animals = Cat | Dog;
const name = createCatName();

这些一起允许非 TypeScript 转译器(如 Babel、swc 或 esbuild)知道可以安全删除哪些导入。

具有 CommonJS 行为的 ES 模块语法 ​

TypeScript具有与CommonJS和AMD直接相关的ES模块语法。在大多数情况下,使用ES模块的导入与这些环境中的导入相同,但此语法可确保TypeScript 文件与CommonJS 输出进行1比1的匹配:require require

ts
import fs = require("fs")
const code = fs.readFileSync("hello.ts", "utf8")

可以在模块参考页中了解有关此语法的详细信息。

CommonJS 语法 ​

CommonJS 是 npm 上大多数模块交付的格式。即使您使用上面的 ES 模块语法进行编写,简要了解 CommonJS 语法的工作原理也将帮助您更轻松地进行调试。

Exporting ​

标识符是通过在名为 的全局变量上设置属性来导出的。 exports module

ts
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

ts
const maths = require("./maths");
maths.pi;

或者你可以使用 JavaScript 中的解构功能来简化一下

ts
const { squareTwo } = require("./maths");
squareTwo;

CommonJS 和 ES 模块互操作 ​

关于默认导入和模块命名空间对象导入之间的区别,CommonJS 和 ES 模块之间的功能不匹配。 TypeScript 有一个编译器标志,可以减少两组不同的约束与 esModuleInterop 之间的摩擦。

TypeScript 的模块解析选项 ​

模块解析是从 or 语句中获取字符串并确定该字符串引用哪个文件的过程。 import require

TypeScript 包含两种解决策略:Classic 和 Node。包含经典(当编译器选项 module 不是 时的默认值)是为了向后兼容。 Node 策略复制了 Node.js 在 CommonJS 模式下的工作方式,并对 和 进行了额外的检查。 commonjs .ts .d.ts

有许多 TSConfig 标志会影响 TypeScript 中的模块策略: moduleResolution 、 baseUrl 、 paths 、 rootDirs 。

关这些策略如何发挥作用的完整详细信息,您可以查阅模块解决方案。

TypeScript 的模块输出选项 ​

有两个选项会影响发出的 JavaScript 输出:

  • target 确定哪些 JS 功能被降级(转换为在较旧的 JavaScript 运行时中运行)以及哪些功能保持不变
  • module 决定模块之间使用什么代码进行交互

您使用哪个 target 由您希望在其中运行 TypeScript 代码的 JavaScript 运行时中可用的功能决定。这可能是:您支持的最旧的 Web 浏览器、您希望使用的 Node.js 的最低版本运行时或可能来自运行时的独特约束 - 例如 Electron。

模块之间的所有通信都是通过模块加载器进行的,编译器选项 module 确定使用哪一个。在运行时,模块加载器负责在执行模块之前查找并执行模块的所有依赖项。

例如,下面是一个使用 ES 模块语法的 TypeScript 文件,展示了 module 的几个不同选项:

ts
import { valueOfPi } from "./constants.js";
 
export const twoPi = valueOfPi * 2;

ES2020 ​

ts
import { valueOfPi } from "./constants.js";
export const twoPi = valueOfPi * 2;

CommonJS ​

ts
"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 ​

ts
(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;
});

TypeScript 命名空间 ​

TypeScript 有自己的模块格式,该格式早于 ES 模块标准。此语法具有许多用于创建复杂定义文件的有用功能,并且在DefinitelyTyped 中仍然得到积极使用。虽然未弃用,但命名空间中的大多数功能都存在于 ES 模块中,我们建议您使用它来与 JavaScript 的方向保持一致。您可以在命名空间参考页面中了解有关命名空间的更多信息。 namespaces