there is a question about esprima and inserting an ast node.
I try to generate one ast node to replace other node with new node , (node = newNode) , but It does't work.
estraverse.traverse(tree, {
enter(node, parent) {
try {
if (node.type === "ExpressionStatement") {
if(node.expression.right.type == "FunctionExpression"){
// the id attribution can be replaced
node.expression.right.id = node.expression.left;
// but node can not be replaced
node = node.expression.right;
node.type = "FunctionDeclaration";
}
}
} catch (error) {
}
},});
Based on the code snippet you shared, you are using estraverse to parse through the AST. For replacing a node, you need to use the estraverse.replace API. You can check the details in the documentation for estraverse.replace, but in general when you find the node to replace (Ex. if(node=='Expression Statement'){ .... }) you need to return the new node to this function which will replace the current node.
//node is replaced by Newnode
One point you need to take care is to make sure the Newnode does not break the AST syntax in anyway. Best way I found was to get the Newnode by converting a code snippet into AST and then grabbing the respective node out of it. This makes sure the structure remains ecmascript compliant.