[英]Traverse a newly replaced node with babel
I would like to add a statement before every function definition, eg 我想在每个函数定义之前添加一条语句,例如
function a() {
var b = function c() {};
}
becomes 变成
foo(function a() {
var b = foo(function c() {});
});
I am trying to achieve this with babel with the following visitor: 我正尝试通过以下访客与babel达成此目标:
var findFunctionVisitor = {
Function: function (path) {
// Traversing further leads to infinite loop as same node is found again
path.stop();
var node = path.node;
// Move every FunctionDeclaration to FunctionExpression
var newNode = t.functionExpression(
node.id,
node.params,
node.body,
node.generator,
node.async
);
path.replaceWith(
t.CallExpression(instrumentationCall, [newNode])
)
// traverse the part in newNode.body
}
};
If I don't stop the path the newly inserted FunctionExpression is found another time which leads to infinite recursion, so the stop is necessary. 如果我不停止该路径,则会再次发现新插入的FunctionExpression,这将导致无限递归,因此必须停止。 My exact problem is, that I don't know how to start the traversing of
newNode.body
, which I would need to get the inner function statements. 我的确切问题是,我不知道如何开始遍历
newNode.body
,这将需要获取内部函数语句。
This may be done by using the babel-traverse module like this: 这可以通过使用像这样的babel-traverse模块来完成:
traverse(newNode, findFunctionVisitor, path.scope, path);
The third argument is a scope and the fourth is a parent path. 第三个参数是作用域,第四个参数是父路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.