如何让Babel输出文件的AST?

时间:2015-11-17 22:20:26

标签: javascript babeljs

有没有办法让Babel输出文件的AST,作为JSON或类似文件,而不是将它压缩回JS?

原因是我希望能够做一些简单的静态分析/代码生成,虽然我的目标是最终在Babel(或类似)的插件中进行,但我觉得如果我可以的话会显着简化从静态模型开始。

2 个答案:

答案 0 :(得分:6)

babylon,babel自己的解析器:

npm install -g babylon

babylon your_file.js > ast.json

Node API示例和来源: https://github.com/babel/babel/tree/master/packages/babylon

同样,babel plugin handbook可能会派上用场参考AST,并开始使用插件开发。

答案 1 :(得分:2)

你应该查看ast-source - 它可以在构建树时将babel作为解析器。

来自他们的npmjs页面的示例:

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");