我想在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"));
            }
        }
    };
}


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

最佳答案

我想到了。
了解如何编写babel插件的最佳场所。 Here

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


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

08-19 09:44