Introduction to ast-query
The ast-query library is a powerful tool for developers to navigate and manipulate Abstract Syntax Trees (AST) with ease. Whether you are refactoring large codebases, generating code dynamically, or performing complex source code transformations, ast-query provides dozens of APIs to help you achieve your goals.
Getting Started with ast-query
To start using ast-query, you need to install it via npm:
npm install ast-query
Useful API Methods in ast-query
Here, we will showcase some of the most useful API methods provided by ast-query along with code snippets to demonstrate their usage.
1. Loading AST
To manipulate an AST, you first need to load it:
const fs = require('fs');
const astQuery = require('ast-query');
const code = fs.readFileSync('example.js', 'utf8');
const ast = astQuery.parse(code);
2. Finding Nodes
You can query nodes within the AST:
const functionNodes = ast.find('FunctionDeclaration');
3. Modifying Nodes
ast-query allows you to easily modify nodes:
functionNodes.attr('type', 'FunctionExpression');
4. Generating Code from AST
After modifying the AST, you can generate code from it:
const modifiedCode = ast.toSource();
fs.writeFileSync('modifiedExample.js', modifiedCode);
Advanced Examples
Let’s take a look at an advanced example where we combine multiple API calls to refactor a function declaration:
const ast = astQuery.parse(fs.readFileSync('example.js', 'utf8'));
// Find function declarations
const functions = ast.find('FunctionDeclaration');
functions.each(function() {
const node = this;
// Rename the function
node.attr('id.name', 'newFunctionName');
// Convert to arrow function
const arrowFunction = astQuery.arrowFunction(node.attr('params'), node.attr('body'));
node.replace(arrowFunction);
});
// Write the modified code back to a file
fs.writeFileSync('refactoredExample.js', ast.toSource());
Building an Application with ast-query
Here is a simple example of an application that uses ast-query to perform automatic code refactoring in a codebase:
const fs = require('fs');
const path = require('path');
const astQuery = require('ast-query');
const directoryPath = path.join(__dirname, 'src');
fs.readdir(directoryPath, function(err, files) {
if (err) {
return console.log('Unable to scan directory: ' + err);
}
files.forEach(function(file) {
const filePath = path.join(directoryPath, file);
const code = fs.readFileSync(filePath, 'utf8');
const ast = astQuery.parse(code);
// Perform refactoring: rename functions, etc.
const functions = ast.find('FunctionDeclaration');
functions.each(function() {
const node = this;
node.attr('id.name', 'newFunctionName');
});
const modifiedCode = ast.toSource();
fs.writeFileSync(filePath, modifiedCode);
console.log(`Refactored ${file}`);
});
});
With this simple application, you can automatically refactor function names in your JavaScript project.
Hash: 221d74ea786ffc5c82de70fd84ee84573d10719bd6498925270ee40de54bc0e4