我正在构建一个插件,该插件可以enterFunction()
通过调用插入到每个现有函数调用的前面path.insertBefore
。所以我的代码是从:
myFunction();
至:
enterFunction();
myFunction();
问题是,当我插入节点时,Babel再次遍历插入的节点。这是日志记录输出:
'CallExpression','myFunction''CallExpression
','enterFunction'
如何防止Babel输入enterFunction
调用表达式及其子级?
这是我当前用于Babel插件的代码:
function(babel) {
return {
visitor: {
CallExpression: function(path) {
console.log("CallExpression", path.node.callee.name)
if (path.node.ignore) {
return;
}
path.node.ignore = true
var enterCall = babel.types.callExpression(
babel.types.identifier("enterFunction"), []
)
enterCall.ignore = true;
path.insertBefore(enterCall)
}
}
}
}
《通天塔手册》提到以下部分:
如果您的插件不需要在特定情况下运行,那么最简单的方法就是写一个提前归还。
BinaryExpression(path) { if (path.node.operator !== '**') return; }
如果要在顶级路径中进行子遍历,则可以使用2种提供的API方法:
path.skip()跳过遍历当前路径的子级。path.stop()完全停止遍历。
outerPath.traverse({ Function(innerPath) { innerPath.skip(); // if checking the children is irrelevant }, ReferencedIdentifier(innerPath, state) { state.iife = true; innerPath.stop(); // if you want to save some state and then stop traversal, or deopt } });
简而言之,用于path.skip()
跳过当前路径的子代。此代码段使用Visitors,CallExpression和skip()演示了此方法的一种应用:
export default function (babel) {
const { types: t } = babel;
return {
name: "ast-transform", // not required
visitor: {
CallExpression(path) {
path.replaceWith(t.blockStatement([
t.expressionStatement(t.yieldExpression(path.node))
]));
path.skip();
}
}
};
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句