问题
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.
回答1:
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.
回答2:
TypeScript compiler doesn't support it but you can do it using recast and babylon@next. Although you will have to trust in the syntax defined by these technologies for representing TypeScript code AST and that they will keep up to date - since TypeScript has new language features release by release (short period of time) - is not like other languages (JavaScript) where you have well defined versions and released in a standard - so if your users start using new language features these technologies (mostly babylon) should keep up to date:
// npm install recast babylon@next
const source = `
interface I {
color: string
}
class C implements I{
color: string='blue'
}
`
const recast = require('recast')
const tsParser = require("recast/parsers/typescript")
const ast = recast.parse(source, {
parser: tsParser
});
console.log(`
CODE:
${source}
AST:
${JSON.stringify(ast)}
`);
来源:https://stackoverflow.com/questions/36505533/how-to-extract-ast-of-given-typescript-code-using-the-open-source-typescript-com