Reputation: 5042
Is there a way I can get Babel to output the AST of a file, as a JSON or similar, rather than condense it back into JS?
The reason is that I want to be able to do some simple static analysis / code gen, and while I aim to eventually do it within a plugin for Babel (or similar), I feel it would simplify things significantly if I can start with a static model.
Upvotes: 3
Views: 4451
Reputation: 722
There's babylon, babel's own parser:
npm install -g babylon
babylon your_file.js > ast.json
Node API example and source: https://github.com/babel/babel/tree/master/packages/babylon
Also the babel plugin handbook might come in handy for AST reference, and to get started with plugin development.
Upvotes: 9
Reputation: 13429
you should check out ast-source - it can take babel
as a parser when it builds the tree.
Example from their npmjs page:
import ASTSource from "ast-source"
import estraverse from "estraverse"
import fs from "fs"
function transform(AST) {
var replaced = {
"type": "babel",
"value": 42,
"raw": "42"
};
return estraverse.replace(AST, {
enter: function (node) {
if (node.type === estraverse.Syntax.Literal) {
return replaced;
}
}
});
}
var source = new ASTSource(fs.readFileSync("./input.js", "utf-8"), {
filePath: "./input.js"
});
var output = source.transform(transform).output();
console.log(output.code);// => "var a = 42;"
console.dir(output.map.toString()); // => source map
fs.writeFileSync("./output.js", output.codeWithMap, "utf-8");
Upvotes: 3