Babel AST Utilities

6.26.0 · active · verified Tue Apr 21

Babel Types (`@babel/types`) is a foundational package within the Babel ecosystem, providing a comprehensive set of utility methods for creating, manipulating, and validating Abstract Syntax Tree (AST) nodes. It adheres to the ESTree specification and Babel's extended AST format, making it essential for anyone writing custom Babel plugins, codemods, or performing static analysis on JavaScript code. The current stable major version is `v7.x`, with the latest being `v7.29.2`, while `v8.x` is in release candidate phase. As part of the Babel monorepo, it follows Babel's frequent release cycle for patches and minors, with major versions introducing significant breaking changes. Its key differentiator is its tight integration and compatibility with Babel's parser (`@babel/parser`) and traverser (`@babel/traverse`), providing canonical builders (e.g., `t.identifier()`), type checkers (e.g., `t.isIdentifier()`), and assertion functions (e.g., `t.assertIdentifier()`) for programmatic AST interaction.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically construct an Abstract Syntax Tree (AST) representing a simple JavaScript arrow function `const add = (a, b) => a + b;` using `babel-types`. It shows the creation of identifiers, expressions, statements, and a full function declaration, then uses `@babel/generator` to convert the AST back into code.

import * as t from '@babel/types';
import generate from '@babel/generator';

// Create identifiers for 'a' and 'b'
const paramA = t.identifier('a');
const paramB = t.identifier('b');

// Create a binary expression 'a + b'
const sumExpression = t.binaryExpression('+', paramA, paramB);

// Create a return statement for 'a + b'
const returnStatement = t.returnStatement(sumExpression);

// Create a block statement for the function body
const functionBody = t.blockStatement([returnStatement]);

// Create an arrow function expression '(...params) => { ...body }'
const arrowFunction = t.arrowFunctionExpression(
  [paramA, paramB], // params
  functionBody,     // body
  false             // async
);

// Create a variable declarator: 'add = (...)'
const declarator = t.variableDeclarator(t.identifier('add'), arrowFunction);

// Create a variable declaration: 'const add = (...)'
const variableDeclaration = t.variableDeclaration('const', [declarator]);

// Wrap the declaration in a Program node
const program = t.program([variableDeclaration]);

// Generate code from the AST (requires @babel/generator)
const { code } = generate(program);
console.log(code);
// Expected output: const add = (a, b) => a + b;

view raw JSON →