gpt4 book ai didi

node.js - 如何使用 require ('typescript' ).transform?

转载 作者:搜寻专家 更新时间:2023-10-30 21:49:19 28 4
gpt4 key购买 nike

const ts = require('typescript');

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

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

最佳答案

您可以使用transpile 函数。这将允许您编译任意字符串:

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;
}

用法:

let diagnostics: typescript.Diagnostic[] = []
let result = transpileWithAllErrors(template, {}, undefined, diagnostics);
for (let err of diagnostics) console.log(err.messageText);
console.log(result);

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

关于node.js - 如何使用 require ('typescript' ).transform?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48455631/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com