带有节点的内存中的Transpile TypeScript

有没有一种方法来在内存中用节点传输TypeScript? 我希望能够在内存中获得生成的JavaScript。

是的,你可以使用TypeScript-Simple:

https://github.com/teppeis/typescript-simple

var tss = require('typescript-simple'); var js = tss('var n: number = 1;'); console.log(js); // 'var n = 1;' 

我们最终开发了基于本地TypeScript transpileModulefunction的解决scheme。

来自TYPESCRIPT DOCS

TranspileModule将使用指定的编译器选项从“input”参数编译源文本。 如果没有提供选项 – 它将使用一组默认的编译器选项。 这个函数将无条件地使用额外的编译器选项:

  • isolatedModules = true
  • allowNonTsExtensions = true
  • noLib = true
  • noResolve = true

transpile() – 这段代码会将TypeScript转换为JavaScript(需要TypeScript中的 typescriptServices.min.js):

 export function transpile(tscode: string): TYPE.EVENT { interface TranspileOptions { compilerOptions?: any fileName?: string; reportDiagnostics?: boolean; moduleName?: string; renamedDependencies?: any; } interface TranspileOutput { outputText: string; diagnostics?: any[]; sourceMapText?: string; } let compilerOptions: ts.CompilerOptions = { isolatedModules: false } let options: TranspileOptions = { compilerOptions: compilerOptions, reportDiagnostics: true // moduleName: modulename } let info: TYPE.EVENT; try { // Transpile the ts code to js. let ret: TranspileOutput = ts.transpileModule(tscode, options); // If diagnostics were returned. // NOTE: The transpiler is currently always return a message (code=5047) about 'isolatedModules', which // is not relavent for our use. If there is more than one row than there is in fact an error. if (ret.diagnostics && ret.diagnostics.length > 0) { let code = ret.diagnostics[0].code; if (code == 5047) { return (info = { success: true, returnvalue: ret.outputText, caller: LibCore.getFunctionName(arguments) }) } else { let text = ret.diagnostics[0].messageText; // let hint = ret.diagnostics[0].file.parseDiagnostics[0].file.nextContainer.symbol.name; return (info = { success: false, returnvalue: ret.diagnostics, message: `Syntax error: ${text} Code: ${code}`, caller: LibCore.getFunctionName(arguments) }) } } else { return (info = { success: true, returnvalue: ret.outputText, caller: LibCore.getFunctionName(arguments) }) } } catch (e) { return (info = { success: false, message: e.message, caller: LibCore.getFunctionName(arguments) }) } } 
Interesting Posts