Registry / serialization / ast-types

ast-types

JSON →
library0.14.2jsnpmunverified

ast-types is a foundational JavaScript library that provides an Esprima-compatible implementation of the Mozilla JavaScript Parser API, specifically designed for working with Abstract Syntax Trees (ASTs). It offers a robust and modular type hierarchy for representing JavaScript code as a tree structure, enabling efficient analysis, transformation, and code generation. The current stable version is `0.14.2`. While widely adopted as a dependency in many JavaScript tooling projects (e.g., Recast, Babel), it maintains a very slow release cadence, suggesting a mature and largely feature-complete state. Key differentiators include its `namedTypes` object for type-safe AST node inspection, `builders` for programmatic AST construction, and a powerful `visit` abstraction for tree traversal and modification. It provides a low-level, high-performance API for direct AST manipulation, often used in transpilers, linters, and code formatters.

npm install ast-types
INSTALL
IMPORT
SIG · AST-TYPES
A
ast-types
serializationjavascriptv0.14.2
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

namedTypes
import { namedTypes as n } from 'ast-types';
const n = require('ast-types').namedTypes;
ESM named import is preferred for `namedTypes` aliased as `n`. While CommonJS `require` works, ESM is recommended for modern Node.js environments.
builders
import { builders as b } from 'ast-types';
const b = require('ast-types').builders;
ESM named import is preferred for `builders` aliased as `b`. `builders` are essential for creating new AST nodes programmatically.
visit
import { visit } from 'ast-types';
const visit = require('ast-types').visit;
The `visit` function is the primary mechanism for traversing an AST. It is a named export.

This quickstart demonstrates parsing JavaScript code into an AST, then using `ast-types`'s `visit` function to traverse the tree. It modifies a variable declarator's identifier and its initializer's literal value, and updates a return statement's argument, finally printing the transformed code.

import { parse, visit, namedTypes as n, builders as b } from 'ast-types'; import { print } from 'recast'; // recast is commonly used with ast-types for printing modified ASTs const code = ` function greet(name) { let message = 'Hello, ' + name + '!'; return message; } `; // Parse the code into an AST const ast = parse(code); // Traverse the AST to find and modify a variable declaration visit(ast, { visitVariableDeclarator(path) { const node = path.node; if (n.Identifier.check(node.id) && node.id.name === 'message') { // Change the variable name from 'message' to 'greeting' node.id = b.identifier('greeting'); // Modify the init expression to include a different greeting // Find the BinaryExpression 'Hello, ' + name + '!' if (n.BinaryExpression.check(node.init)) { // Replace 'Hello, ' with 'Greetings, ' if (n.BinaryExpression.check(node.init.left) && n.Literal.check(node.init.left.left)) { node.init.left.left.value = 'Greetings, '; } } } this.traverse(path); // Continue traversing children }, visitReturnStatement(path) { const node = path.node; // Update the returned identifier if it was 'message' if (n.Identifier.check(node.argument) && node.argument.name === 'message') { node.argument.name = 'greeting'; } this.traverse(path); // Continue traversing children } }); // Print the modified AST back to code const modifiedCode = print(ast).code; console.log(modifiedCode); /* Expected Output: function greet(name) { let greeting = 'Greetings, ' + name + '!'; return greeting; } */
Debug
Known issues
gotchaWhen modifying the AST during traversal, ensure you understand how `path.replace()` and `path.prune()` affect the tree. Incorrect usage, especially with `prune()`, can lead to unexpected tree structures or omitted nodes. `path.prune()` removes the current node and prevents its children from being visited, effectively stopping traversal down that branch.
fix
Carefully review the documentation for `NodePath` methods. For complex modifications, consider creating new nodes with `builders` and using `path.replace()` to swap out subtrees, or building a new AST from scratch. Always test transformations thoroughly.
affects: >=0.1.0
gotcha`ast-types` has a very slow release cadence, with the latest version `0.14.2` published over six years ago (as of 2026). While stable, this means it may not immediately support the newest ECMAScript syntax features without a compatible parser (like Babel's parser or `meriyah` with proper configuration) providing the AST first.
fix
Ensure that the parser you use (e.g., `Esprima`, `Babylon`/`@babel/parser`, `meriyah`) is up-to-date and generates ASTs compatible with the ESTree specification that `ast-types` expects. If working with very new JS features, you might need to combine `ast-types` with a more frequently updated parser and potentially `recast` to handle new node types gracefully.
affects: <=0.14.2
gotchaWhile `ast-types` ships with TypeScript types, incorrect configuration of `esModuleInterop` or `allowSyntheticDefaultImports` in `tsconfig.json` can lead to issues with `import` statements, particularly in mixed CommonJS/ESM environments.
fix
For optimal compatibility in TypeScript projects, set `"esModuleInterop": true` and `"moduleResolution": "Bundler"` (or `"NodeNext"`) in your `tsconfig.json`. When importing CommonJS modules into ESM, you may need `import * as pkg from 'pkg';` or dynamic `await import('pkg');` if default exports are not handled implicitly.
affects: >=0.1.0
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading 'body')
Attempting to traverse or manipulate an AST that was not correctly parsed or is empty.
fix
Ensure the input code is valid and that the parser function (e.g., `parse` from `recast` or a direct parser like `esprima`) executed successfully and returned a valid AST object before attempting to access its properties.
Error: Unknown type X. Please define it using types.def(...);
You are attempting to create an AST node type (or a builder is attempting to create one) that `ast-types` does not recognize or has not been explicitly defined in its type hierarchy. This often happens with custom AST extensions or if the parser produces non-standard nodes.
fix
If the type is a standard ESTree node, ensure your `ast-types` version supports it. If it's a custom or non-standard node, you may need to define it using `types.def('MyCustomNode', { ... });` before trying to use it with builders or traversal.
Upgrade
Version history
0.14.2latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
20 hits · last 30 days
node
16
OpenAI (training)
1
Resources