我想在我的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”存在于树的某处。我希望第一次转换只在第二次转换完成后才会发生。我如何实现这一目标。?
答案 0 :(得分:1)
我明白了。 了解如何编写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”访问者中遍历..;)
答案 1 :(得分:0)
以下是一些有用的链接,用于编写自定义babel访客插件。
https://babeljs.io/docs/en/6.26.3/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);
}