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.
Asked
Active
Viewed 1,731 times
3 Answers
1
(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. Since you indicated that you want to add code to js files, you'll need to add it to a node with a body
. How you manipulate the body
is the same as how you do with arrays (using acorn as an example). The following is an example of how you add a node to a FunctionDeclaration
node.
// 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

Binary
- 451
- 5
- 15
-1
What I found useful was using estraverse with acorn. You can convert your JS files into AST using acorn and then easily add or replace nodes with estraverse according to the ECMAscript.
What you need to look for is the estraverse.replace(..) API.
-3
I believe this is what you are looking for https://github.com/SBoudrias/ast-query

jfmmm
- 381
- 1
- 3
- 15
-
He said "Link-only answers can become invalid if the linked page changes" .. but in this case if the repo is down the explanation would be useless anyway. The second link to the yeoman doc only point to the repo without explanation on how to use this with yeoman. So the essencial part of the answer is the link to the repo. Plus the original poster don't give enought context about is need for me to explain how to use this in his case. So why not just just let the original poster possibly get an answer to is question instead of leaving it forever unanswered. – jfmmm Apr 15 '18 at 04:05