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

How to use acorn.js or similar library to add a new node to the ast tree?

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

我相信这就是您要找的东西https://github.com/SBoudrias/ast-query

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

您需要寻找的是 estraverse.replace(..) API.

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

你首先要明白,并不是简单地在任何地方向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