如何让 Babel 输出文件的 AST?

How do I get Babel to output a file's AST?

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

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

你应该看看 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");

babylon,babel自带的解析器:

npm install -g babylon

babylon your_file.js > ast.json


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

此外,babel plugin handbook 可能会派上用场作为 AST 参考,并开始插件开发。