Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Babel plugin: How to get the path for a given node?

I'm writing a Babel plugin that needs to manipulate every top-level declaration in a code file, that is, every declaration that is directly below the Program node.

The Babel Plugin Handbook says 'Do not traverse when manual lookup will do', explaining that I can simply iterate over the child nodes. That works fine. My problem is that all the manipulation functions -- replaceWith, insertBefore, insertAfter, etc. -- are defined on paths, not on nodes. So when I'm iterating over the child nodes, how can I manipulate them?

It seems to me that I need some way of getting a path object from a given node. But I could only find documentation for the reverse case: getting the node from a path object (path.node).

like image 735
Daniel Wolf Avatar asked Apr 26 '17 17:04

Daniel Wolf


1 Answers

You cannot get a path from a node because a node does not know where in the AST it is.

The point that part is trying to make is that you should avoid calling path.traverse when you can do path.get("foo"), so for Program you can do

Program(path) {
  path.get("body").forEach((child) => {
    // "child" here is a NodePath
  });
},
like image 140
loganfsmyth Avatar answered Sep 20 '22 13:09

loganfsmyth