What is @types/estraverse?
@types/estraverse provides TypeScript type definitions for the estraverse library, which is a tool for ECMAScript/JavaScript syntax tree traversal. It allows developers to walk through and manipulate the abstract syntax tree (AST) of JavaScript code.
What are @types/estraverse's main functionalities?
Traversing the AST
This feature allows you to traverse the AST of JavaScript code. The `enter` and `leave` methods are called when entering and leaving each node in the AST, respectively.
const estraverse = require('estraverse');
const ast = { /* some AST */ };
estraverse.traverse(ast, {
enter: function (node, parent) {
console.log('Entering node:', node.type);
},
leave: function (node, parent) {
console.log('Leaving node:', node.type);
}
});
Replacing nodes in the AST
This feature allows you to replace nodes in the AST. In this example, all identifiers with the name 'oldName' are replaced with 'newName'.
const estraverse = require('estraverse');
const ast = { /* some AST */ };
const newAst = estraverse.replace(ast, {
enter: function (node) {
if (node.type === 'Identifier' && node.name === 'oldName') {
node.name = 'newName';
}
}
});
Custom node visitor keys
This feature allows you to define custom visitor keys for traversing non-standard AST nodes. In this example, a custom node type 'CustomNode' with a child node 'childNode' is defined.
const estraverse = require('estraverse');
const ast = { /* some AST */ };
const visitorKeys = {
CustomNode: ['childNode']
};
estraverse.traverse(ast, {
enter: function (node) {
console.log('Entering node:', node.type);
}
}, visitorKeys);
Other packages similar to @types/estraverse
esprima
Esprima is a high-performance, standard-compliant ECMAScript parser that can be used to generate an AST from JavaScript code. While it focuses on parsing, it can be used in conjunction with other tools for AST traversal and manipulation.
babel-traverse
babel-traverse is a tool from the Babel ecosystem that allows for efficient traversal and manipulation of the AST. It provides more advanced features and integrations with Babel plugins and transformations compared to estraverse.
acorn
Acorn is a small, fast, JavaScript-based JavaScript parser that generates an AST. While it is primarily focused on parsing, it can be extended with plugins to support AST traversal and manipulation.