JavaScript 在处理模块化代码的不同方法方面有着悠久的历史。自 2012 年以来,TypeScript 已经实现了对许多这些格式的支持,但随着时间的推移,社区和 JavaScript 规范已经汇聚在一种称为 ES 模块(或 ES6 模块)的格式上。你可能知道它是 import
/export
语法。
¥JavaScript has a long history of different ways to handle modularizing code.
Having been around since 2012, TypeScript has implemented support for a lot of these formats, but over time the community and the JavaScript specification has converged on a format called ES Modules (or ES6 modules). You might know it as the import
/export
syntax.
ES Modules 于 2015 年被添加到 JavaScript 规范中,到 2020 年在大多数 Web 浏览器和 JavaScript 运行时得到广泛支持。
¥ES Modules was added to the JavaScript spec in 2015, and by 2020 had broad support in most web browsers and JavaScript runtimes.
作为重点,该手册将涵盖 ES 模块及其流行的前驱 CommonJS module.exports =
语法,你可以在 模块 下的参考部分中找到有关其他模块模式的信息。
¥For focus, the handbook will cover both ES Modules and its popular pre-cursor CommonJS module.exports =
syntax, and you can find information about the other module patterns in the reference section under Modules.
JavaScript 模块是如何定义的
¥How JavaScript Modules are Defined
在 TypeScript 中,就像在 ECMAScript 2015 中一样,任何包含顶层 import
或 export
的文件都被视为一个模块。
¥In TypeScript, just as in ECMAScript 2015, any file containing a top-level import
or export
is considered a module.
相反,没有任何顶层导入或导出声明的文件被视为其内容在全局作用域内可用的脚本(因此也可用于模块)。
¥Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).
模块在它们自己的作用域内执行,而不是在全局作用域内。这意味着在模块中声明的变量、函数、类等在模块外部是不可见的,除非它们使用一种导出形式显式导出。相反,要使用从不同模块导出的变量、函数、类、接口等,必须使用其中一种导入形式导入。
¥Modules are executed within their own scope, not in the global scope. This means that variables, functions, classes, etc. declared in a module are not visible outside the module unless they are explicitly exported using one of the export forms. Conversely, to consume a variable, function, class, interface, etc. exported from a different module, it has to be imported using one of the import forms.
非模块
¥Non-modules
在开始之前,了解 TypeScript 将什么视为模块非常重要。JavaScript 规范声明任何没有 import
声明、export
或顶层 await
的 JavaScript 文件都应被视为脚本而不是模块。
¥Before we start, it’s important to understand what TypeScript considers a module.
The JavaScript specification declares that any JavaScript files without an import
declaration, export
, or top-level await
should be considered a script and not a module.
在脚本文件中,变量和类型被声明在共享全局作用域内,并且假设你将使用 outFile
编译器选项将多个输入文件连接到一个输出文件中,或者在 HTML 中使用多个 <script>
标记来加载这些文件(按正确的顺序!)。
¥Inside a script file variables and types are declared to be in the shared global scope, and it’s assumed that you’ll either use the outFile
compiler option to join multiple input files into one output file, or use multiple <script>
tags in your HTML to load these files (in the correct order!).
如果你的文件当前没有任何 import
或 export
,但你希望将其视为模块,请添加以下行:
¥If you have a file that doesn’t currently have any import
s or export
s, but you want to be treated as a module, add the line:
tsTry
export {};
这会将文件更改为不导出任何内容的模块。无论你的模块目标如何,此语法都有效。
¥which will change the file to be a module exporting nothing. This syntax works regardless of your module target.
TypeScript 中的模块
¥Modules in TypeScript
补充阅读:
不耐烦的 JS(模块)
MDN:JavaScript 模块
在 TypeScript 中编写基于模块的代码时,需要考虑三件事:
¥There are three main things to consider when writing module-based code in TypeScript:
-
语法:我想用什么语法来导入和导出东西?
¥Syntax: What syntax do I want to use to import and export things?
-
模块解析:模块名称(或路径)与磁盘上的文件有什么关系?
¥Module Resolution: What is the relationship between module names (or paths) and files on disk?
-
模块输出目标:我触发的 JavaScript 模块应该是什么样子?
¥Module Output Target: What should my emitted JavaScript module look like?
ES 模块语法
¥ES Module Syntax
一个文件可以通过 export default
声明一个主导出:
¥A file can declare a main export via export default
:
tsTry
// @filename: hello.tsexport default functionhelloWorld () {console .log ("Hello, world!");}
然后通过以下方式导入:
¥This is then imported via:
tsTry
importhelloWorld from "./hello.js";helloWorld ();
除了默认导出之外,你还可以通过省略 default
通过 export
导出多个变量和函数:
¥In addition to the default export, you can have more than one export of variables and functions via the export
by omitting default
:
tsTry
// @filename: maths.tsexport varpi = 3.14;export letsquareTwo = 1.41;export constphi = 1.61;export classRandomNumberGenerator {}export functionabsolute (num : number) {if (num < 0) returnnum * -1;returnnum ;}
这些可以通过 import
语法在另一个文件中使用:
¥These can be used in another file via the import
syntax:
tsTry
import {pi ,phi ,absolute } from "./maths.js";console .log (pi );constabsPhi =absolute (phi );
附加导入语法
¥Additional Import Syntax
可以使用 import {old as new}
之类的格式重命名导入:
¥An import can be renamed using a format like import {old as new}
:
tsTry
import {pi asπ } from "./maths.js";console .log (π );
你可以将上述语法混合并匹配到单个 import
中:
¥You can mix and match the above syntax into a single import
:
tsTry
// @filename: maths.tsexport constpi = 3.14;export default classRandomNumberGenerator {}// @filename: app.tsimportRandomNumberGenerator , {pi asπ } from "./maths.js";RandomNumberGenerator ;console .log (π );
你可以使用 * as name
将所有导出的对象放入单个命名空间中:
¥You can take all of the exported objects and put them into a single namespace using * as name
:
tsTry
// @filename: app.tsimport * asmath from "./maths.js";console .log (math .pi );constpositivePhi =math .absolute (math .phi );
你可以通过 import "./file"
导入文件,但不将任何变量包含到当前模块中:
¥You can import a file and not include any variables into your current module via import "./file"
:
tsTry
// @filename: app.tsimport "./maths.js";console .log ("3.14");
在这种情况下,import
什么也不做。但是,maths.ts
中的所有代码都已评估,这可能会触发影响其他对象的副作用。
¥In this case, the import
does nothing. However, all of the code in maths.ts
was evaluated, which could trigger side-effects which affect other objects.
TypeScript 特定的 ES 模块语法
¥TypeScript Specific ES Module Syntax
可以使用与 JavaScript 值相同的语法导出和导入类型:
¥Types can be exported and imported using the same syntax as JavaScript values:
tsTry
// @filename: animal.tsexport typeCat = {breed : string;yearOfBirth : number };export interfaceDog {breeds : string[];yearOfBirth : number;}// @filename: app.tsimport {Cat ,Dog } from "./animal.js";typeAnimals =Cat |Dog ;
TypeScript 扩展了 import
语法,其中包含两个用于声明类型导入的概念:
¥TypeScript has extended the import
syntax with two concepts for declaring an import of a type:
import type
这是一个只能导入类型的导入语句:
¥Which is an import statement which can only import types:
tsTry
// @filename: animal.tsexport typeCat = {breed : string;yearOfBirth : number };export typeDog = {breeds : string[];yearOfBirth : number };export constcreateCatName = () => "fluffy";// @filename: valid.tsimport type {Cat ,Dog } from "./animal.js";export typeAnimals =Cat |Dog ;// @filename: app.tsimport type {createCatName } from "./animal.js";const'createCatName' cannot be used as a value because it was imported using 'import type'.1361'createCatName' cannot be used as a value because it was imported using 'import type'.name =(); createCatName
内联 type
导入
¥Inline type
imports
TypeScript 4.5 还允许单个导入以 type
为前缀,以指示导入的引用是一种类型:
¥TypeScript 4.5 also allows for individual imports to be prefixed with type
to indicate that the imported reference is a type:
tsTry
// @filename: app.tsimport {createCatName , typeCat , typeDog } from "./animal.js";export typeAnimals =Cat |Dog ;constname =createCatName ();
这些一起允许像 Babel、swc 或 esbuild 这样的非 TypeScript 转译器知道可以安全地删除哪些导入。
¥Together these allow a non-TypeScript transpiler like Babel, swc or esbuild to know what imports can be safely removed.
具有 CommonJS 行为的 ES 模块语法
¥ES Module Syntax with CommonJS Behavior
TypeScript 具有与 CommonJS 和 AMD require
直接相关的 ES 模块语法。在大多数情况下,使用 ES 模块的导入与这些环境中的 require
相同,但这种语法可确保你的 TypeScript 文件与 CommonJS 输出有 1 对 1 的匹配:
¥TypeScript has ES Module syntax which directly correlates to a CommonJS and AMD require
. Imports using ES Module are for most cases the same as the require
from those environments, but this syntax ensures you have a 1 to 1 match in your TypeScript file with the CommonJS output:
tsTry
importfs = require("fs");constcode =fs .readFileSync ("hello.ts", "utf8");
你可以在 模块参考页面 中了解有关此语法的更多信息。
¥You can learn more about this syntax in the modules reference page.
CommonJS 语法
¥CommonJS Syntax
CommonJS 是 npm 上大多数模块的交付格式。即使你使用上面的 ES 模块语法进行编写,对 CommonJS 语法的工作原理有一个简要的了解也会帮助你更轻松地进行调试。
¥CommonJS is the format which most modules on npm are delivered in. Even if you are writing using the ES Modules syntax above, having a brief understanding of how CommonJS syntax works will help you debug easier.
导出
¥Exporting
通过在名为 module
的全局上设置 exports
属性来导出标识符。
¥Identifiers are exported via setting the exports
property on a global called module
.
tsTry
functionabsolute (num : number) {if (num < 0) returnnum * -1;returnnum ;}module .exports = {pi : 3.14,squareTwo : 1.41,phi : 1.61,absolute ,};
然后可以通过 require
语句导入这些文件:
¥Then these files can be imported via a require
statement:
tsTry
constmaths =require ("./maths");maths .pi ;
或者你可以使用 JavaScript 中的解构功能进行一些简化:
¥Or you can simplify a bit using the destructuring feature in JavaScript:
tsTry
const {squareTwo } =require ("./maths");squareTwo ;
CommonJS 和 ES 模块互操作
¥CommonJS and ES Modules interop
关于默认导入和模块命名空间对象导入之间的区别,CommonJS 和 ES 模块之间的功能不匹配。TypeScript 有一个编译器标志来减少与 esModuleInterop
的两组不同约束之间的摩擦。
¥There is a mis-match in features between CommonJS and ES Modules regarding the distinction between a default import and a module namespace object import. TypeScript has a compiler flag to reduce the friction between the two different sets of constraints with esModuleInterop
.
TypeScript 的模块解析选项
¥TypeScript’s Module Resolution Options
模块解析是从 import
或 require
语句中获取字符串并确定该字符串所指的文件的过程。
¥Module resolution is the process of taking a string from the import
or require
statement, and determining what file that string refers to.
TypeScript 包含两种解析策略:经典和 Node。Classic 是编译器选项 module
不是 commonjs
时的默认值,包含在内以实现向后兼容性。Node 策略复制了 Node.js 在 CommonJS 模式下的工作方式,并额外检查了 .ts
和 .d.ts
。
¥TypeScript includes two resolution strategies: Classic and Node. Classic, the default when the compiler option module
is not commonjs
, is included for backwards compatibility.
The Node strategy replicates how Node.js works in CommonJS mode, with additional checks for .ts
and .d.ts
.
有许多 TSConfig 标志会影响 TypeScript 中的模块策略:moduleResolution
, baseUrl
, paths
, rootDirs
.
¥There are many TSConfig flags which influence the module strategy within TypeScript: moduleResolution
, baseUrl
, paths
, rootDirs
.
有关这些策略如何发挥作用的完整详细信息,你可以查阅 模块解析 参考页。
¥For the full details on how these strategies work, you can consult the Module Resolution reference page.
TypeScript 的模块输出选项
¥TypeScript’s Module Output Options
有两个选项会影响触发的 JavaScript 输出:
¥There are two options which affect the emitted JavaScript output:
-
target
确定哪些 JS 功能被降级(转换为在较旧的 JavaScript 运行时中运行),哪些保持不变¥
target
which determines which JS features are downleveled (converted to run in older JavaScript runtimes) and which are left intact -
module
确定模块之间使用什么代码进行交互¥
module
which determines what code is used for modules to interact with each other
你使用哪个 target
取决于你希望在其中运行 TypeScript 代码的 JavaScript 运行时中可用的功能。那可能是:你支持的最旧的 Web 浏览器、你期望运行的 Node.js 的最低版本或可能来自运行时的独特约束 - 例如 Electron。
¥Which target
you use is determined by the features available in the JavaScript runtime you expect to run the TypeScript code in. That could be: the oldest web browser you support, the lowest version of Node.js you expect to run on or could come from unique constraints from your runtime - like Electron for example.
模块之间的所有通信都是通过模块加载器进行的,编译器选项 module
确定使用哪一个。在运行时,模块加载器负责在执行模块之前定位和执行模块的所有依赖。
¥All communication between modules happens via a module loader, the compiler option module
determines which one is used.
At runtime the module loader is responsible for locating and executing all dependencies of a module before executing it.
例如,这是一个使用 ES Modules 语法的 TypeScript 文件,展示了 module
的几个不同选项:
¥For example, here is a TypeScript file using ES Modules syntax, showcasing a few different options for module
:
tsTry
import {valueOfPi } from "./constants.js";export consttwoPi =valueOfPi * 2;
ES2020
tsTry
import { valueOfPi } from "./constants.js";export const twoPi = valueOfPi * 2;
CommonJS
tsTry
"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
tsTry
(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
相同。¥Note that ES2020 is effectively the same as the original
index.ts
.
你可以看到所有可用的选项以及它们触发的 JavaScript 代码在 module
的 TSConfig 参考手册 中的样子。
¥You can see all of the available options and what their emitted JavaScript code looks like in the TSConfig Reference for module
.
TypeScript 命名空间
¥TypeScript namespaces
TypeScript 有自己的模块格式,称为 namespaces
,它早于 ES 模块标准。这种语法对于创建复杂的定义文件有很多有用的特性,并且仍然被积极使用 在绝对类型。虽然没有被弃用,但命名空间中的大部分功能都存在于 ES 模块中,我们建议你使用它来与 JavaScript 的方向保持一致。你可以在 命名空间参考页面 中了解有关命名空间的更多信息。
¥TypeScript has its own module format called namespaces
which pre-dates the ES Modules standard. This syntax has a lot of useful features for creating complex definition files, and still sees active use in DefinitelyTyped. While not deprecated, the majority of the features in namespaces exist in ES Modules and we recommend you use that to align with JavaScript’s direction. You can learn more about namespaces in the namespaces reference page.