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

Babel plugin (Visitor pattern) - How it works

我想在我的 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" 访问者中遍历.. ;)

这里有一些有助于编写自定义 babel 访问者插件的链接。

https://babeljs.io/docs/en/babel-types

https://github.com/jamiebuilds/babel-handbook/blob/master/translations/en/plugin-handbook.md

https://babeljs.io/docs/en/babel-standalone

如果你想在node js中做,你需要安装@babel-core

npm install --save-dev @babel/core

下面是一些示例代码:

let babel = require("@babel/core");
let fs = require('fs');

fs.readFile('testcase1client.js', 'utf8', function(err, tc1c)
{
    if(err)
        console.log(err);

    let out1 = babel.transform(tc1c, { plugins: [
    {
        visitor: {
            FunctionExpression(path) {
                // console.log(path.parent.id.name);

            },
            CallExpression(path) {
                // console.log(path.node.callee.name);
                
            }
        }
    }]});

    console.log(out1.code);
}