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-typesVerified import paths — ran on the pinned version, not inferred.
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.
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.
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.
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.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.
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.No dependency data recorded yet.