如何使用 acorn.js 或类似的库向 ast 树添加新节点



我试图使用橡子.js和 yeoman 一起向现有的 js 文件添加代码。我尝试使用 esprima 和 acorn 来完成这项工作,但我找不到任何关于将节点添加到 AST 的文档。

(晚了三年,但这是答案(

您需要首先了解,不是简单地将新节点添加到任何地方的 AST 树中。由于您指示要向 js 文件添加代码,因此需要将其添加到具有 body 的节点。操作body的方式与处理数组的方式相同(以 acorn 为例(。下面是如何将节点添加到FunctionDeclaration节点的示例。

// astNode is a FunctionDeclaration node with a body that contains more nodes
// newNode is the code you want to insert
astNode.body.push(newNode); // add node at the end of the function block
astNode.body.unshift(newNode); // add node at the beginning of the function block
astNode.body.splice(index, 0, newNode); // add node at index

我发现有用的是将 estraverse 与橡子一起使用。您可以使用 acorn 将 JS 文件转换为 AST,然后根据 ECMAscript 轻松地用 estraverse 添加或替换节点。

你需要寻找的是 estraverse.replace(..(应用程序接口。

我相信

这就是你要找的 https://github.com/SBoudrias/ast-query

最新更新