Babel 插件(访客模式)——它是如何工作的

Aft*_*han 4 javascript visitor-pattern babeljs

我想在我的 babel 插件中做两个替换。第二次更换只能在第一次更换完成后进行。

module.exports = function(babel) {
    const t = babel.types;
    return {
        visitor: {
            FunctionExpression: function(path) {
                //Conversion to arrow functions
                path.replaceWith(t.arrowFunctionExpression(path.node.params, path.node.body, false));
            },
            ThisExpression: function(path) {
                //Converting all this expressions to identifiers so that it won't get translated differently
                path.replaceWith(t.identifier("this"));
            }
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

在我的“FunctionExpression”的 AST 树中,“ThisExpression”存在于树下的某个位置。我希望仅在第二次转换完成后才进行第一次转换。我该如何实现这一点?

Aft*_*han 5

我想到了。了解如何编写 babel 插件的最佳地点。这里

module.exports = function(babel) {
    const t = babel.types;
    return {
        visitor: {
            FunctionExpression: {
                enter: function(path) {
                    path.traverse(updateThisExpression);
                    //Conversion to arrow functions
                    let arrowFnNode = t.arrowFunctionExpression(path.node.params,
                        path.node.body, false);
                    path.replaceWith(arrowFnNode);
                }
            }
        }
    };
}

const updateThisExpression = {
    ThisExpression: {
        enter: function(path) {
            //Converting all this expressions to identifiers so that
            //it won't get translated differently
            path.replaceWith(t.identifier("this"));
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

您编写另一个访问者对象,用于在“FunctionExpression”访问者中遍历。.;)