Babel插件(访客模式)-如何工作

nkhmeac6  于 2022-12-08  发布在  Babel
关注(0)|答案(2)|浏览(500)

我想在我的巴别塔插件中做两个替换。第二个替换应该只在第一个完成后发生。

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”位于树的某个位置。我希望第一次转换只在第二次转换完成后发生。我如何实现这一点?

vuktfyat

vuktfyat1#

我想出来了。了解如何编写巴别塔插件的最佳地方。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”访问者中遍历。)

hvvq6cgz

hvvq6cgz2#

这里有一些有用的链接来编写自定义巴别塔访问者插件。
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
如果要在节点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);
}

相关问题