简体   繁体   English

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

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

I was trying to use acorn.js along with yeoman to add code to existing js files.I have tried to work with esprima and acorn to do this job but I cannot find any documentation about adding node to the AST.我试图使用 acorn.js 和 yeoman 将代码添加到现有的 js 文件。我尝试使用 esprima 和 acorn 来完成这项工作,但我找不到任何关于将节点添加到 AST 的文档。

(three years late but here's the answer) (晚了三年,但这是答案)

You need to first understand that one does not simply add a new node to the AST tree anywhere.您需要首先了解,一个人不会简单地在任何地方向 AST 树添加一个新节点。 Since you indicated that you want to add code to js files, you'll need to add it to a node with a body .由于您表示要将代码添加到 js 文件,因此您需要将其添加到带有body的节点。 How you manipulate the body is the same as how you do with arrays (using acorn as an example).操作body的方式与操作数组的方式相同(以橡子为例)。 The following is an example of how you add a node to a FunctionDeclaration node.以下示例说明如何将节点添加到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

What I found useful was using estraverse with acorn.我发现有用的是将 estraverse 与橡子一起使用。 You can convert your JS files into AST using acorn and then easily add or replace nodes with estraverse according to the ECMAscript.您可以使用 acorn 将 JS 文件转换为 AST,然后根据 ECMAscript 使用 estraverse 轻松添加或替换节点。

What you need to look for is the estraverse.replace(..) API.您需要寻找的是 estraverse.replace(..) API。

I believe this is what you are looking for https://github.com/SBoudrias/ast-query我相信这就是您要找的东西https://github.com/SBoudrias/ast-query

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM