gpt4 book ai didi

babeljs - 我可以防止Babel遍历插件插入的代码吗?

转载 作者:行者123 更新时间:2023-12-03 12:19:44 26 4
gpt4 key购买 nike

我正在构建一个插件,该插件通过调用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)
}
}
}
}

最佳答案

Babel Handbook提到以下部分:

If your plugin needs to not run in a certain situation, the simpliest thing to do is to write an early return.

BinaryExpression(path) {
if (path.node.operator !== '**') return;
}

If you are doing a sub-traversal in a top level path, you can use 2 provided API methods:

path.skip() skips traversing the children of the current path. path.stop() stops traversal entirely.

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()跳过遍历当前路径的子级。
this snippet using Visitors, CallExpression and 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();
}
}
};
}

关于babeljs - 我可以防止Babel遍历插件插入的代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39961906/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com