跳到内容

原生运行 TypeScript

🌐 Running TypeScript Natively

你可以直接在 Node.js 中编写有效的 TypeScript 代码,而无需先对其进行转译。

🌐 You can write code that's valid TypeScript directly in Node.js without the need to transpile it first.

如果你使用的是 v22.18.0 或更高版本,并且你的源代码仅包含可擦除的 TypeScript 语法,你可以在不使用任何标志的情况下执行 TypeScript 代码。

🌐 If you are using v22.18.0 or later and your source code contains only erasable TypeScript syntax, you can execute TypeScript code without any flags.

node example.ts

如果你使用的版本低于 v22.18.0,可以使用 --experimental-strip-types 标志直接在 Node.js 中运行 TypeScript 文件。

🌐 If you are using a version less than v22.18.0, you can use the --experimental-strip-types flag to run TypeScript files directly in Node.js.

node --experimental-strip-types example.ts

就是这样!你现在可以在 Node.js 中直接运行 TypeScript 代码,而无需先进行转译,并且可以使用 TypeScript 来捕获类型相关的错误。

🌐 And that's it! You can now run TypeScript code directly in Node.js without the need to transpile it first, and use TypeScript to catch type-related errors.

如果需要,你可以通过 --no-experimental-strip-types 标志来禁用它。

🌐 You can disable it via --no-experimental-strip-types flag if needed.

node --no-experimental-strip-types example.ts

在 v22.7.0 中,添加了标志 --experimental-transform-types,用于启用仅限 TypeScript 的需要转换的语法,例如 enumnamespace。启用 --experimental-transform-types 会自动意味着 --experimental-strip-types 已启用,因此无需在同一命令中同时使用这两个标志:

🌐 In v22.7.0 the flag --experimental-transform-types was added to enable TypeScript-only syntax that requires transformation, like enums and namespace. Enabling --experimental-transform-types automatically implies that --experimental-strip-types is enabled, so there's no need to use both flags in the same command:

node --experimental-transform-types another-example.ts

此标志是可选的,你仅应在代码需要时使用它。

🌐 This flag is opt-in, and you should only use it if your code requires it.

约束

🌐 Constraints

Node.js 对 TypeScript 的支持有一些需要注意的限制:

🌐 The support for TypeScript in Node.js has some constraints to keep in mind:

你可以在 API 文档 上获取更多信息。

🌐 You can get more information on the API docs.

配置

🌐 Configuration

Node.js TypeScript 加载器(Amaro)在运行 TypeScript 代码时不需要也不使用 tsconfig.json

🌐 The Node.js TypeScript loader (Amaro) does not need or use tsconfig.json to run TypeScript code.

我们建议通过创建一个使用 这里 列出的 compilerOptionstsconfig.json 来配置你的编辑器和 tsc 以反映 Node.js 的行为,同时使用 TypeScript 版本 5.7 或更高

🌐 We recommend configuring your editor and tsc to reflect Node.js behavior by creating a tsconfig.json using the compilerOptions listed here, as well as using TypeScript version 5.7 or higher.