module.stripTypeScriptTypes(code[, options])
稳定性: 1.2 - 发布候选版
code<string> 要去除类型注解的代码。options<Object>- 返回值:<string> 删除类型注解后的代码。
module.stripTypeScriptTypes()会从 TypeScript 代码中移除类型注解。它可以用于在使用vm.runInContext()或vm.compileFunction()运行 TypeScript 代码之前去除类型注解。默认情况下,如果代码包含需要转换的 TypeScript 特性(如Enums),会抛出错误,更多信息请参见 类型剥离。当 mode 为'transform'时,它还会将 TypeScript 特性转换为 JavaScript,更多信息请参见 转换 TypeScript 功能。当 mode 为'strip'时,不会生成源地图,因为位置被保留。如果提供了sourceMap,在 mode 为'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, ...