简体   繁体   English

Babel插件:如何获取给定节点的路径?

[英]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 . 我的问题是所有的操作函数 - replaceWithinsertBeforeinsertAfter等 - 都是在路径上定义的,而不是在节点上定义的。 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.

相关问题 Babel 插件:如何插入兄弟节点 - Babel Plugin: How to insert a sibling node 如何在 babel 插件中遍历 Path 的范围 - How do I traverse the scope of a Path in a babel plugin JS创建babel插件:如何获取匿名函数的参数 - JS creating babel plugin: how to get arguments of anonymous function (babel plugin) TypeError: Path was expected to have a container - (babel plugin) TypeError: Path was expected to have a container 如何让 babel-node 将 Workers 引用的文件转换为 commonjs? (就像 babel 一样) - How to get babel-node to convert files referenced by Workers to commonjs? (like babel does) 如何在遍历期间从 Babel 节点获取代码作为字符串 - How to get code as a string from Babel node during traverse 如何在Babel 6中定义插件设置? - How to define plugin settings in babel 6? 如何使用 babel-plugin-module-resolver 为根路径设置别名并禁用其他根导入? - How to use babel-plugin-module-resolver to set an alias for the root path and disable other root imports? 递归获取嵌套对象中给定节点的完整路径(父层次结构) - Recursively get full path (parents hierarchy) of a given node in a nested object 如何安装节点模块@babel/plugin-transform-class-properties? - How do I install node module @babel/plugin-transform-class-properties?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM