简体   繁体   中英

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:

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. 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.

This may be done by using the babel-traverse module like this:

traverse(newNode, findFunctionVisitor, path.scope, path);

The third argument is a scope and the fourth is a parent path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM