TypeScript Office - 模块
# 模块
JavaScript 有很长的历史,有不同的方式来处理模块化的代码。TypeScript 从 2012 年开始出现,已经实现了对许多这些格式的支持,但随着时间的推移,社区和 JavaScript 规范已经趋向于一种名为 ES 模块(或 ES6 模块)的格式。你可能知道它是 import/export 语法。
ES Modules 在 2015 年被加入到 JavaScript 规范中,到 2020 年,在大多数网络浏览器和 JavaScript 运行时中都有广泛的支持。
为了突出重点,本内容将涵盖 ES Modules 及其流行的前驱 CommonJS module.exports =
语法。
# 如何定义 JavaScript 模块
在 TypeScript 中,就像在 ECMAScript 2015 中一样,任何包含顶级 import 或 export 的文件都被认为是一个模块。
相反,一个没有任何顶级导入或导出声明的文件被视为一个脚本,其内容可在全局范围内使用(因此也可用于模块)。
模块在自己的范围内执行,而不是在全局范围内。这意味着在模块中声明的变量、函数、类等在模块外是不可见的,除非它们被明确地用某种导出形式导出。相反,要使用从不同模块导出的变量、函数、类、接口等,必须使用导入的形式将其导入。
# 非模块
在我们开始之前,重要的是要了解 TypeScript 认为什么才是模块。JavaScript 规范声明,任何没有 export 或顶层 await 的 JavaScript 文件都应该被认为是一个脚本而不是一个模块。
在一个脚本文件中,变量和类型被声明为在共享的全局范围内,并且假定你会使用 outFile 编译器选项将多个输入文件加入一个输出文件,或者在你的 HTML 中使用多个 <script>
标签来加载这些文件(顺序正确)。
如果你有一个目前没有任何导入或导出的文件,但你希望被当作一个模块来处理,请添加这一行:
export {};
这将改变该文件,使其成为一个什么都不输出的模块。无论你的模块目标是什么,这个语法都有效。
# TypeScript 中的模块
在 TypeScript 中编写基于模块的代码时,有三个主要方面需要考虑:
- 语法:我想用什么语法来导入和导出东西?
- 模块解析:模块名称(或路径)和磁盘上的文件之间是什么关系?
- 模块输出目标:我编译出来的 JavaScript 模块应该是什么样子的?
# ES 模块语法
一个文件可以通过 export default 声明一个主要出口:
// @filename: hello.ts
export default function helloWorld() {
console.log("Hello, world!");
}
2
3
4
然后通过以下方式导入:
import hello from "./hello.js";
hello();
2
除了默认的导出,你还可以通过省略 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;
}
2
3
4
5
6
7
8
9
这些可以通过 import 语法在另一个文件中使用:
import { pi, phi, absolute } from "./maths.js";
console.log(pi);
// const absPhi: number
const absPhi = absolute(phi);
2
3
4
# 额外的导入语法
可以使用 import {old as new}
这样的格式来重命名一个导入:
import { pi as π } from "./maths.js";
// (alias)
var π: number
// import π
console.log(π);
2
3
4
5
你可以将上述语法混合并匹配到一个单一的 import 中:
// @filename: maths.ts
export const pi = 3.14;
export default class RandomNumberGenerator {}
// @filename: app.ts
import RNGen, { pi as π } from "./maths.js";
// (alias) class RNGen
// import RNGen
RNGen;
// (alias) const π: 3.14
// import π
console.log(π);
2
3
4
5
6
7
8
9
10
11
12
13
你可以把所有导出的对象,用 * as name ,把它们放到一个命名空间:
// @filename: app.ts
import * as math from "./maths.js";
console.log(math.pi);
// const positivePhi: number
const positivePhi = math.absolute(math.phi);
2
3
4
5
6
你可以通过 import "./file"
导入一个文件,而不把任何变量纳入你的当前模块:
// @filename: app.ts
import "./maths.js";
console.log("3.14");
2
3
在这种情况下,import 没有任何作用。然而,maths.ts 中的所有代码都被解析了,这可能引发影响其他对象的副作用。
# TypeScript 特定的 ES 模块语法
类型可以使用与 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;
2
3
4
5
6
7
8
9
10
TypeScript 用两个概念扩展了 import 语法,用于声明一个类型的导入。
- import type
这是一个导入语句,只能导入类型:
// @filename: animal.ts
export type Cat = { breed: string; yearOfBirth: number };
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();
2
3
4
5
6
7
8
9
10
11
12
- 内联类型导入
TypeScript 4.5 还允许以 type 为前缀的单个导入,以表明导入的引用是一个类型:
// @filename: app.ts
import { createCatName, type Cat, type Dog } from "./animal.js";
export type Animals = Cat | Dog;
const name = createCatName();
2
3
4
# ES 模块语法与 CommonJS 行为
TypeScript 有 ES Module 语法,它直接与 CommonJS 和 AMD 的 require 相关联。使用 ES Module 的 import 在大多数情况下与这些环境的 require 相同,但这种语法确保你在 TypeScrip 文件中与 CommonJS 的输出有 1 对 1 的匹配:
import fs = require("fs");
const code = fs.readFileSync("hello.ts", "utf8");
2
# 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,
};
2
3
4
5
6
7
8
9
10
然后这些文件可以通过 require 语句导入:
const maths = require("maths");
// pi: any
maths.pi;
2
3
或者你可以使用 JavaScript 中的析构功能来简化一下:
const { squareTwo } = require("maths");
// const squareTwo: any
squareTwo;
2
3
# CommonJS 和 ES 模块的互操作性
关于默认导入和模块命名空间对象导入之间的区别,CommonJS 和 ES Modules 之间存在着功能上的不匹配。
这个后面章节会详细介绍。
# TypeScript的模块解析选项
模块解析是指从 import 或 require 语句中获取一个字符串,并确定该字符串所指的文件的过程。
TypeScript 包括两种解析策略:经典和 Node。当编译器选项 module 不是 commonjs 时,经典策略是默认的,是为了向后兼容。Node 策略复制了 Node.js 在 CommonJS 模式下的工作方式,对 .ts
和 .d.ts
有额外的检查。
在TypeScript中,有许多TSConfig标志影响模块策略:moduleResolution
,baseUrl
,path
,rootDirs
。
# TypeScript 的模块输出选项
有两个选项会影响 JavaScript 输出:
- target,它决定了哪些 JS 功能被降级(转换为在旧的 JavaScript 运行时运行),哪些保持不变
- module,它决定了哪些代码用于模块之间的相互作用
你使用的 target 是由你期望运行 TypeScript 代码的 avaScript 运行时中的可用功能决定的。这可能是:你支持的最古老的网络浏览器,你期望运行的最低版本的 Node.js,或者可能来自于你的运行时的独特约束,比如 Electron。
所有模块之间的通信都是通过模块加载器进行的,编译器选项 module 决定使用哪一个。在运行时,模块加载器负责在执行一个模块之前定位和执行该模块的所有依赖项。
例如,这里是一个使用 ES 模块语法的 TypeScript 文件,展示了 module 的一些不同选项:
import { valueOfPi } from "./constants.js";
export const twoPi = valueOfPi * 2;
2
ES2020
import { valueOfPi } from "./constants.js";
export const twoPi = valueOfPi * 2;
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;
2
3
4
5
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;
});
2
3
4
5
6
7
8
9
10
11
12
13
14
15
请注意,ES2020 实际上与原来的 index.ts 相同。
你可以在 TSConfig 模块参考 (opens new window) 中看到所有可用的选项以及它们发出的 JavaScript 代码是什么样子。
# TypeScript 命名空间
TypeScript 有自己的模块格式,称为命名空间(namespaces),这比 ES 模块标准要早。这种语法对于创建复杂的定义文件有很多有用的功能,并且在 DefinitelyTyped 中仍然被积极使用。虽然没有被废弃,但命名空间中的大部分功能都存在于 ES Module s中,我们建议你使用它来与 JavaScript 的方向保持一致。你可以在 namespaces 参考页中了解更多关于命名空间的信息。