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.
The AST (Abstract Syntax Tree) quickly comes to your mind to approach this problem. The AST is a data structure to represent the structure of your source file in a format readable by machines. Indeed, if I throw the above example in the TypeScript AST Viewer I get immediate access to the AST.
The TypeScript compiler compiles these files and outputs the JavaScript with . js extension by keeping the same file name as the individual input file. The TypeScript compiler also preserves the original file path, hence the . js output file will be generated where the input file was in the directory structure.
An AST is the result of parsing code. For JavaScript, an AST is a JavaScript object containing a tree representation of your source. Before we use it, we have to create it. Depending on the code we are parsing, we choose the appropriate parser. Here since the code is ES5-compatible, we can choose the acorn parser.
Basic code:
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());
}
});
});
So if you provided that with a C:\MyFile.ts
like:
class MyClass {}
interface MyInterface {}
It would output MyClass
and MyInterface
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With