简体   繁体   中英

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

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
  });
},

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