本文介绍了如何使用开源 Typescript 编译器代码提取给定 Typescript 代码的 AST?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,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 {}

它会输出 MyClassMyInterface.

弄清楚我刚刚展示的内容之外的所有内容需要大量工作.查看和/或帮助您为这项正在进行的工作做出贡献可能对您更有益.

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!