AST Parser
ast-parser is a JavaScript and TypeScript utility library designed to simplify the traversal and extraction of information from Abstract Syntax Trees (ASTs), particularly those generated by `@babel/parser`. At version 0.2.0, it is in an early development stage, focused on providing helper functions like `parse`, `find`, and `findInfo` to navigate complex AST structures efficiently. While its release cadence is not formally established due to its nascent state, it appears to be actively developed, shipping with TypeScript types for enhanced developer experience. Its primary differentiation lies in offering a more declarative way to query and inspect AST nodes, complementing the output of parsers like Babel, rather than replacing them. This allows developers to easily locate specific node types or properties within a given code's AST representation.
Common errors
-
TypeError: Cannot read properties of undefined (reading 'nodeType')
cause The AST node passed to an `ast-parser` function (like `parse`, `find`, or `findInfo`) is `null` or `undefined`, or it lacks the expected `nodeType` property.fixVerify that the input to `ast-parser` functions is a valid, non-null Babel AST node. Often this occurs if the initial Babel parsing failed or if a `find` operation returned no results and its output was subsequently used. -
Error: nodeType must be a string
cause The `nodeType` argument for `find` or `findInfo` functions was not provided as a string.fixPass a string literal representing the desired AST node type, e.g., `find('ObjectExpression', ...)` instead of `find(ObjectExpression, ...)`.
Warnings
- breaking As of version 0.2.0, `ast-parser` is in early development. APIs are subject to change without major version bumps. Always review the latest documentation upon updating.
- gotcha This library is designed to process ASTs generated by `@babel/parser` and does not parse code directly. You must use `@babel/parser` (or a compatible alternative) to generate the initial AST.
Install
-
npm install ast-parser -
yarn add ast-parser -
pnpm add ast-parser
Imports
- parse
const { parse } = require('ast-parser');import { parse } from 'ast-parser'; - find
const { find } = require('ast-parser');import { find } from 'ast-parser'; - findInfo
const { findInfo } = require('ast-parser');import { findInfo } from 'ast-parser';
Quickstart
import { parse as babelParse } from '@babel/parser';
import { parse, find, findInfo } from 'ast-parser';
// Helper to get a Babel AST node from code
function getBabelAst(code: string) {
return babelParse(code, {
sourceType: 'module',
plugins: ['classProperties', 'typescript', 'decorators-legacy'],
});
}
// Example 1: Basic AST parsing and node type assertion
const astNode = parse(getBabelAst('const x = 10;').program);
console.log(`Parsed AST node type: ${astNode.nodeType}`);
// Expected: Parsed AST node type: Program
// Example 2: Finding specific nodes
const codeWithObject = `
const myVar = { key1: 'value1', key2: 123 };
`;
const objectExpressionInfo = find('ObjectExpression', getBabelAst(codeWithObject));
console.log(`Found ObjectExpression string: ${objectExpressionInfo.string}`);
// Expected: Found ObjectExpression string: { key1: 'value1', key2: 123 }
// Example 3: Finding child information within a node
const objectProperties = findInfo('ObjectProperty', objectExpressionInfo);
objectProperties.forEach(prop => {
console.log(` Property: ${prop.key.string} = ${prop.value.string}`);
});
/* Expected:
Property: key1 = 'value1'
Property: key2 = 123
*/
// Example 4: Finding class properties and methods
const classCode = `
class MyClass {
static id: string = 'abc';
private name: string;
constructor(name: string) { this.name = name; }
public greet(): string { return 'Hello, ' + this.name; }
}
`;
const classDeclaration = find('ClassDeclaration', getBabelAst(classCode));
console.log(`Class declaration string: ${classDeclaration.string}`);
// Expected: Class declaration string: class MyClass
const classProperties = findInfo('ClassProperty', classDeclaration);
console.log(`Found ${classProperties.length} class properties.`);
const classMethods = findInfo('ClassMethod', classDeclaration);
console.log(`Found ${classMethods.length} class methods.`);
// Expected: Found 2 class properties.
// Expected: Found 2 class methods.