module.stripTypeScriptTypes(code[, options])
稳定性: 1.2 - 发布候选版
module.stripTypeScriptTypes() 可以从 TypeScript 代码中移除类型注解。它可以在使用 vm.runInContext() 或 vm.compileFunction() 运行 TypeScript 代码之前,用于去除类型注解。
默认情况下,如果代码包含需要转换的 TypeScript 特性(例如 enum),它将抛出错误。有关更多信息,请参见 类型剥离。
🌐 By default, it will throw an error if the code contains TypeScript features
that require transformation, such as enums. See type-stripping for more information.
警告: 由于 TypeScript 解析器的变化,该函数的输出在不同的 Node.js 版本中不应被视为稳定。
🌐 WARNING: The output of this function should not be considered stable across Node.js versions, due to changes in the TypeScript parser.
import { stripTypeScriptTypes } from 'node:module';
const code = 'const a: number = 1;';
const strippedCode = stripTypeScriptTypes(code);
console.log(strippedCode);
// Prints: const a = 1;const { stripTypeScriptTypes } = require('node:module');
const code = 'const a: number = 1;';
const strippedCode = stripTypeScriptTypes(code);
console.log(strippedCode);
// Prints: const a = 1;如果提供了 sourceUrl,它将作为注释附加在输出的末尾:
🌐 If sourceUrl is provided, it will be used appended as a comment at the end of the output:
import { stripTypeScriptTypes } from 'node:module';
const code = 'const a: number = 1;';
const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' });
console.log(strippedCode);
// Prints: const a = 1\n\n//# sourceURL=source.ts;const { stripTypeScriptTypes } = require('node:module');
const code = 'const a: number = 1;';
const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' });
console.log(strippedCode);
// Prints: const a = 1\n\n//# sourceURL=source.ts;