[英]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. 我正在编写一个Babel插件,需要操作代码文件中的每个顶级声明,即直接在
Program
节点下面的每个声明。
The Babel Plugin Handbook says 'Do not traverse when manual lookup will do' , explaining that I can simply iterate over the child nodes. Babel插件手册说“手动查找时不要遍历” ,解释说我可以简单地迭代子节点。 That works fine.
这很好。 My problem is that all the manipulation functions --
replaceWith
, insertBefore
, insertAfter
, etc. -- are defined on paths , not on nodes . 我的问题是所有的操作函数 -
replaceWith
, insertBefore
, insertAfter
等 - 都是在路径上定义的,而不是在节点上定义的。 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
). 但我只能找到相反案例的文档:从路径对象(
path.node
)获取节点。
You cannot get a path from a node because a node does not know where in the AST it is. 您无法从节点获取路径,因为节点不知道它在AST中的位置。
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 这个部分试图做的是你应该避免在你可以做
path.get("foo")
时调用path.traverse
,所以对于Program
你可以做
Program(path) {
path.get("body").forEach((child) => {
// "child" here is a NodePath
});
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.