javascriptabstract-syntax-treeesprima

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.


Solution

  • (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