Node.js 如何使用require(';typescript';).transform?

Node.js 如何使用require(';typescript';).transform?,node.js,typescript,Node.js,Typescript,如何在上述操作中转换字符串 您可以使用transfile功能。这将允许您编译任意字符串: const ts = require('typescript'); let template = ` let hello: string = 'hello,world'; ` ts.transform 编辑 上面的解决方案是可行的,但它只检查语法错误,而不检查语义错误。进行模块解析并检查语义错误的版本为: import * as typescript from 'typescript'

如何在上述操作中转换字符串

您可以使用
transfile
功能。这将允许您编译任意字符串:

const ts = require('typescript');

let template = `
         let hello: string = 'hello,world';
`
ts.transform
编辑

上面的解决方案是可行的,但它只检查语法错误,而不检查语义错误。进行模块解析并检查语义错误的版本为:

import * as typescript from 'typescript';  

let template = `
         let hello: string = 'hello,world';
         class test{}
`
let errors : typescript.Diagnostic[] = []
let result = typescript.transpile(template, {}, undefined, errors);

// The result
console.log(result);
// The erorrs
for(let err of errors) console.log(err.messageText);
用法:

function transpileWithAllErrors(input: string, compilerOptions?: typescript.CompilerOptions, fileName: string = "dynamic.ts", diagnostics?: typescript.Diagnostic[]): string {
    let result: string;
    let host = typescript.createCompilerHost({});
    let sourceFile = typescript.createSourceFile(fileName, template, typescript.ScriptTarget.ES5);
    let orginalGetSourceFile = host.getSourceFile;
    host.getSourceFile = (file, languageVersion, onError, shouldCreateNewSourceFile) =>
        file == fileName ?
            sourceFile :
            orginalGetSourceFile(file, languageVersion, onError, shouldCreateNewSourceFile);

    host.getCurrentDirectory = () => "";
    host.getDefaultLibLocation = () => "node_modules/typescript/lib";
    host.getDefaultLibFileName = () => "node_modules/typescript/lib/lib.d.ts";

    let program = typescript.createProgram([fileName], {}, host);

    // Capture output, 
    host.writeFile = (wFileName, data) =>{ 
        if(wFileName.endsWith(".js")) {
            result = data;
        }
    };

    if (diagnostics != null) {
        diagnostics.push(...program.getSyntacticDiagnostics(sourceFile));
        diagnostics.push(...program.getSemanticDiagnostics(sourceFile));
        diagnostics.push(...program.getOptionsDiagnostics());
    }
    program.emit(sourceFile);
    return result;
}

注意:此方法不解析相对于当前路径的模块,因此脚本可以访问当前路径中安装的任何模块。另外,我没有对代码进行广泛的测试,但它应该可以工作。

您想使用typescript编译器编译字符串
模板
?是的,我想这样做谢谢,您知道有一种检查语法错误的方法吗@付延伟 修改答案以获取错误并记录函数a(c:text){console.log('aaaaaa')},但是,这篇文章仍然可以顺利编译,没有“text”变量@付延伟 是的,
transfile
不提供导出语义错误,只提供语法错误。我不知道这是为什么,我正在寻找一个替代方案,但似乎没有@付延伟 我正在制作一个版本,我非常接近,但我现在没有时间完成。我将在明天之前更新答案,以包括符号错误,不幸的是,它不仅仅是一个简单的方法调用。
let diagnostics: typescript.Diagnostic[] = []
let result = transpileWithAllErrors(template, {}, undefined, diagnostics);
for (let err of diagnostics) console.log(err.messageText);
console.log(result);