What is estraverse?
The estraverse npm package is a utility for traversing and updating ECMAScript (JavaScript) abstract syntax trees (ASTs). It is commonly used in the development of JavaScript code analysis and transformation tools.
What are estraverse's main functionalities?
Traversing an AST
This feature allows you to traverse an AST, visiting all nodes in a depth-first order. You can perform actions when entering or leaving each node.
const estraverse = require('estraverse');
const ast = { /* some AST object */ };
estraverse.traverse(ast, {
enter: function (node) {
console.log('Entering node:', node.type);
},
leave: function (node) {
console.log('Leaving node:', node.type);
}
});
Updating an AST
This feature allows you to update nodes in an AST during traversal. In this example, it renames identifiers from 'oldName' to 'newName'.
const estraverse = require('estraverse');
const ast = { /* some AST object */ };
estraverse.replace(ast, {
enter: function (node) {
if (node.type === 'Identifier' && node.name === 'oldName') {
node.name = 'newName';
return node;
}
}
});
Other packages similar to estraverse
acorn
Acorn is a tiny, fast JavaScript parser that produces an AST which can be used by tools like estraverse. While Acorn focuses on parsing, estraverse focuses on traversal and modification.
babel-traverse
Babel-traverse is part of the Babel compiler ecosystem. It allows for traversing the Babel-generated AST and has more features specific to Babel's AST format, compared to estraverse which is more generic.
esquery
Esquery is a package for querying an AST using a CSS-like query syntax. It is different from estraverse in that it focuses on selecting nodes based on complex patterns rather than traversing every node.
recast
Recast provides AST traversal and transformation capabilities, similar to estraverse, but also includes pretty-printing and source map support, which estraverse does not.