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);
注:このメソッドは、現在のパスに関連するモジュール解決を行うため、スクリプトは現在のパスにインストールされているすべてのモジュールにアクセスできます。また、コードの広範なテストは行いませんでしたが、機能するはずです。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加