Introduction to ast-query
The ast-query library is a powerful AST (Abstract Syntax Tree) tool for manipulating JavaScript code. This article delves into the various APIs provided by ast-query
and includes numerous examples to demonstrate its capabilities.
Getting Started with ast-query
First, let’s start by installing the library:
npm install ast-query
Then, you can include it in your project as follows:
const query = require('ast-query');
API Examples
1. Parsing JavaScript Code
const ast = query('const x = 42;');
console.log(ast.toString());
// Output: const x = 42;
2. Finding Variable Declarations
const ast = query('const x = 42; let y = "hello";');
const variables = ast.find('VariableDeclaration');
console.log(variables.length);
// Output: 2
3. Replacing Identifiers
const ast = query('const x = 42;');
ast.find('Identifier', { name: 'x' }).replace('y');
console.log(ast.toString());
// Output: const y = 42;
4. Removing Nodes
const ast = query('const x = 42; const y = "hello";');
ast.find('VariableDeclaration', { kind: 'const' }).remove();
console.log(ast.toString());
// Output:
5. Adding Statements
const ast = query('const x = 42;');
ast.body.append('let y = "world";');
console.log(ast.toString());
// Output: const x = 42; let y = "world";
App Example Using ast-query
Let’s create a simple refactoring tool that replaces all occurrences of var
with let
in a given JavaScript code.
const query = require('ast-query');
function refactorVarToLet(jsCode) {
const ast = query(jsCode);
ast.find('VariableDeclaration', { kind: 'var' }).replace(node => {
node.kind = 'let';
});
return ast.toString();
}
// Example usage
const originalCode = 'var a = 1; var b = 2;';
const refactoredCode = refactorVarToLet(originalCode);
console.log(refactoredCode);
// Output: let a = 1; let b = 2;
By running the above example, you can see how ast-query
helps in rewriting JavaScript code dynamically. This is just a simple demonstration of ast-query’s powerful capabilities in JavaScript AST manipulation.