Astring: Fast ESTree Code Generator

1.9.0 · active · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates parsing a JavaScript string into an ESTree AST using Acorn, then generating formatted code from that AST using Astring, including comments and custom indentation. It also shows using environment variables for dynamic values.

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);

view raw JSON →