用 babel 遍历一个新替换的节点

Traverse a newly replaced node with babel

我想在每个函数定义之前添加一条语句,例如

function a() {
  var b = function c() {};
}

变成

foo(function a() {
  var b = foo(function c() {});
});

我正尝试通过以下访问者使用 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
  }
};

如果我不停止路径,新插入的 FunctionExpression 会在另一次找到导致无限递归,所以停止是必要的。 我的确切问题是,我不知道如何开始遍历 newNode.body,我需要得到内部函数语句。

这可以通过使用 babel-traverse 模块来完成,如下所示:

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

第三个参数是范围,第四个是父路径。