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
).
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
});
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With