module.stripTypeScriptTypes(code[, options])
稳定性: 1.2 - 发布候选版
code<string> 用于去除类型注解的代码。options<Object>- 返回:<string> 带有类型注解的代码已被移除。
module.stripTypeScriptTypes()可以从 TypeScript 代码中移除类型注解。它可以在使用vm.runInContext()或vm.compileFunction()运行之前,用于剥离 TypeScript 代码中的类型注解。默认情况下,如果代码中包含需要转换的 TypeScript 特性(例如Enums),将会抛出错误,更多信息请参见 类型剥离。当模式为'transform'时,它还会将 TypeScript 特性转换为 JavaScript,更多信息请参见 转换 TypeScript 功能。当模式为'strip'时,不会生成源映射,因为位置得以保留。如果提供了sourceMap,在模式为'strip'时,将会抛出错误。
警告: 由于 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;当 mode 为 'transform' 时,代码将被转换为 JavaScript:
🌐 When mode is 'transform', the code is transformed to JavaScript:
import { stripTypeScriptTypes } from 'node:module';
const code = `
namespace MathUtil {
export const add = (a: number, b: number) => a + b;
}`;
const strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true });
console.log(strippedCode);
// Prints:
// var MathUtil;
// (function(MathUtil) {
// MathUtil.add = (a, b)=>a + b;
// })(MathUtil || (MathUtil = {}));
// # sourceMappingURL=data:application/json;base64, ...const { stripTypeScriptTypes } = require('node:module');
const code = `
namespace MathUtil {
export const add = (a: number, b: number) => a + b;
}`;
const strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true });
console.log(strippedCode);
// Prints:
// var MathUtil;
// (function(MathUtil) {
// MathUtil.add = (a, b)=>a + b;
// })(MathUtil || (MathUtil = {}));
// # sourceMappingURL=data:application/json;base64, ...