使用运行器运行 TypeScript
¥Running TypeScript with a runner
如果你想要比内置支持更高级的 TypeScript 处理(或者你使用的是 v22.7.0 之前的 Node.js),你有 2 个选项:使用运行器(它可以为你处理大部分复杂性),或者通过 transpilation 自行处理所有问题。
¥If you want more advanced processing of TypeScript than the built-in support (or you're using Node.js prior to v22.7.0), you have 2 options: use a runner (which handles much of the complexity for you), or handle it all yourself via transpilation.
使用 ts-node
运行 TypeScript 代码
¥Running TypeScript code with ts-node
ts-node 是 Node.js 的 TypeScript 执行环境。它允许你直接在 Node.js 中运行 TypeScript 代码,而无需先编译它。默认情况下,ts-node
执行类型检查,除非启用 transpileOnly
。虽然 ts-node
可以在运行时捕获类型错误,但我们仍建议在发布代码之前先使用 tsc
对其进行类型检查。
¥ts-node is a TypeScript execution environment for Node.js. It allows you to run TypeScript code directly in Node.js without the need to compile it first. By default, ts-node
performs type checking unless transpileOnly
is enabled. While ts-node
can catch type errors at runtime, we still recommend type-checking your code first with tsc
before shipping it.
要使用 ts-node
,你需要先安装它:
¥To use ts-node
, you need to install it first:
npm i -D ts-node
然后你可以像这样运行你的 TypeScript 代码:
¥Then you can run your TypeScript code like this:
npx ts-node example.ts
使用 tsx
运行 TypeScript 代码
¥Running TypeScript code with tsx
tsx 是 Node.js 的另一个 TypeScript 执行环境。它允许你直接在 Node.js 中运行 TypeScript 代码,而无需先编译它。但请注意,它不会对你的代码进行类型检查。因此,我们建议在交付之前先使用 tsc
对代码进行类型检查,然后使用 tsx
运行它。
¥tsx is another TypeScript execution environment for Node.js. It allows you to run TypeScript code directly in Node.js without the need to compile it first. Note, however, that it does not type check your code. So we recommend to type check your code first with tsc
and then run it with tsx
before shipping it.
要使用 tsx
,你需要先安装它:
¥To use tsx
, you need to install it first:
npm i -D tsx
然后你可以像这样运行你的 TypeScript 代码:
¥Then you can run your TypeScript code like this:
npx tsx example.ts
通过 node
注册 tsx
¥Registering tsx
via node
如果你想通过 node
使用 tsx
,你可以通过 --import
注册 tsx
:
¥If you want to use tsx
via node
, you can register tsx
via --import
:
node --import=tsx example.ts