如何使用开源Typescript编译器代码提取给定Typescript代码的AST? [英] How to Extract AST of given Typescript code using the open source Typescript compiler code?
问题描述
众所周知,Typescript现在是完全开源的。可在 Tyescript 中找到。我正在构建一个应用程序,它将获取Typescript代码作为输入并输出给定代码的AST。为我提供一种提取输入Typescript代码的AST(抽象语法树)的适当方法,而不是对其进行编译并将其转换为Javascript。
As it is known that Typescript is completely opensource now. which is available at Tyescript. I am building an application that will get Typescript code as input and give output the AST of the given code. Provide me a proper way to extract this AST(Abstract Syntax Tree) of input Typescript code rather than comppliling it and converting it into Javascript.
推荐答案
基本代码:
const fileNames = ["C:\\MyFile.ts"];
const compilerOptions: ts.CompilerOptions = {
// compiler options go here if any...
// look at ts.CompilerOptions to see what's available
};
const program = ts.createProgram(fileNames, compilerOptions);
const typeChecker = program.getTypeChecker();
const sourceFiles = program.getSourceFiles();
sourceFiles.filter(f => /MyFile\.ts$/.test(f.fileName)).forEach(sourceFile => {
ts.forEachChild(sourceFile, node => {
const declaration = node as ts.Declaration;
if (declaration.name) {
console.log(declaration.name.getText());
}
});
});
因此,如果您提供了 C:\MyFile.ts
,例如:
So if you provided that with a C:\MyFile.ts
like:
class MyClass {}
interface MyInterface {}
它将输出 MyClass
和 MyInterface
。
弄清楚除我刚刚显示的内容以外的所有工作。查看和/或帮助您为这项工作正在进行 a>。
Figuring out everything beyond what I've just shown is a lot of work. It might be more beneficial for you to look at and/or help contribute to this work in progress.
这篇关于如何使用开源Typescript编译器代码提取给定Typescript代码的AST?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!