Daniel Schmidt
Daniel Schmidt

Reputation: 11921

Traverse a newly replaced node with babel

I would like to add a statement before every function definition, e.g.

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.

Upvotes: 1

Views: 2753

Answers (1)

Daniel Schmidt
Daniel Schmidt

Reputation: 11921

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.

Upvotes: 2

Related Questions