类型剥离


【Type stripping】

--no-experimental-strip-types 标志会阻止 Node.js 运行 TypeScript 文件。默认情况下,Node.js 只会执行不包含需要转换的 TypeScript 功能(如枚举)的文件。Node.js 会将内联类型注释替换为空格,并且不会进行类型检查。要启用这些功能的转换,请使用 --experimental-transform-types 标志。依赖于 tsconfig.json 设置的 TypeScript 功能,例如路径或者将较新的 JavaScript 语法转换为较旧标准,是故意不支持的。要获得完整的 TypeScript 支持,请参见 完全支持 TypeScript

【The flag --no-experimental-strip-types prevents Node.js from running TypeScript files. By default Node.js will execute only files that contain no TypeScript features that require transformation, such as enums. Node.js will replace inline type annotations with whitespace, and no type checking is performed. To enable the transformation of such features use the flag --experimental-transform-types. TypeScript features that depend on settings within tsconfig.json, such as paths or converting newer JavaScript syntax to older standards, are intentionally unsupported. To get full TypeScript support, see Full TypeScript support.】

类型剥离功能旨在轻量化。通过有意不支持需要生成 JavaScript 代码的语法,并通过用空白替换内联类型,Node.js 可以运行 TypeScript 代码而无需使用源映射。

【The type stripping feature is designed to be lightweight. By intentionally not supporting syntaxes that require JavaScript code generation, and by replacing inline types with whitespace, Node.js can run TypeScript code without the need for source maps.】

类型剥离兼容大多数版本的 TypeScript,但我们建议使用 5.8 或更高版本,并使用以下 tsconfig.json 设置:

【Type stripping is compatible with most versions of TypeScript but we recommend version 5.8 or newer with the following tsconfig.json settings:】

{
  "compilerOptions": {
     "noEmit": true, // Optional - see note below
     "target": "esnext",
     "module": "nodenext",
     "rewriteRelativeImportExtensions": true,
     "erasableSyntaxOnly": true,
     "verbatimModuleSyntax": true
  }
} 

如果你打算只执行 *.ts 文件,例如构建脚本,可以使用 noEmit 选项。如果你打算分发 *.js 文件,则不需要这个标志。

【Use the noEmit option if you intend to only execute *.ts files, for example a build script. You won't need this flag if you intend to distribute *.js files.】