Astring: Fast ESTree Code Generator
Astring is a lightweight and high-performance JavaScript code generator that transforms an ESTree-compliant Abstract Syntax Tree (AST) back into JavaScript source code. Currently at version 1.9.0, the library sees frequent minor and patch releases, indicating active development and responsiveness to new language features and bug fixes. Its key differentiators include exceptional speed (outperforming alternatives like Babel, Escodegen, and Prettier by significant margins), a tiny footprint (approx. 4 KB gzipped), and zero runtime dependencies. Astring supports JavaScript up to ES2024 and stage 3 proposals, can be extended with custom AST node handlers, and integrates with source map and comment generation tools. It's compatible with ASTs produced by parsers such as Acorn and Meriyah, and runs in Node.js, browsers, and Deno.
Common errors
-
TypeError: generate is not a function
cause Attempting to use `require('astring')` or `import generate from 'astring'` when `generate` is a named export.fixUse correct named import syntax: `import { generate } from 'astring';` for ESM or `const { generate } = require('astring');` for CommonJS. -
TypeError: Cannot read properties of undefined (reading 'type')
cause The AST node being processed by `astring.generate` is either `undefined`, `null`, or does not conform to the expected ESTree structure (e.g., missing a `type` property).fixInspect the input AST to ensure it's a valid ESTree-compliant object and that all its nodes have a `type` property. This often happens if the parsing failed or a transformation corrupted the AST.
Warnings
- gotcha Astring relies on `String.prototype.repeat` and `String.prototype.endsWith`. If targeting older JavaScript environments (e.g., IE) that lack these methods, you must include appropriate polyfills (e.g., `string.prototype.repeat`, `string.prototype.endsWith`, or `babel-polyfill`) for Astring to function correctly.
- gotcha Astring expects an ESTree-compliant AST. Feeding it a malformed or non-compliant AST, or one generated by a parser with significant deviations from the ESTree spec, may result in incorrect code generation or runtime errors.
- gotcha Enabling comment generation (`comments: true`) or providing complex custom generators can impact performance. While Astring is designed for speed, these options add overhead and should be considered carefully in performance-critical applications.
Install
-
npm install astring -
yarn add astring -
pnpm add astring
Imports
- generate
const generate = require('astring');import { generate } from 'astring'; - GENERATOR
const { GENERATOR } = require('astring');import { GENERATOR } from 'astring'; - astring (global)
import { generate } from './dist/astring.min.js';// In HTML: <script src="astring.min.js"></script> // In JS: var generate = astring.generate;
Quickstart
import { generate } from 'astring';
import * as acorn from 'acorn'; // npm install acorn
const sourceCode = `
const add = (a, b) => {
// This is a simple addition function
return a + b;
};
function subtract(x, y) {
return x - y;
}
const result = add(process.env.NUM_ONE ?? '5', process.env.NUM_TWO ?? '3');
console.log('Result:', result);
`;
// Parse the source code into an ESTree-compliant AST
const ast = acorn.parse(sourceCode, {
ecmaVersion: 2024, // Use a recent ECMAScript version
sourceType: 'module',
});
// Generate code from the AST with specific options
const generatedCode = generate(ast, {
indent: ' ', // Use 2 spaces for indentation
lineEnd: '\n', // Use newline for line endings
comments: true, // Enable comment generation
});
console.log('--- Original Source ---\n' + sourceCode);
console.log('\n--- Generated Code ---\n' + generatedCode);