原生运行 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 专用语法,例如 enum 和 namespace。启用 --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)不需要或使用 tsconfig.json 来运行 TypeScript 代码。
¥The Node.js TypeScript loader (Amaro) does not need or use tsconfig.json to run TypeScript code.
我们建议配置你的编辑器和 tsc 以反映 Node.js 行为,方法是使用 compilerOptions 列出的 此处 创建 tsconfig.json,以及使用 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.