Serialize ESTree to JavaScript

2.0.0 · active · verified Sun Apr 19

estree-util-to-js is a focused utility designed to transform an ESTree (and ESast) syntax tree into a serialized JavaScript string. Its primary function is to convert in-memory syntax representations back into executable code, often after parsing and transformation within an AST processing pipeline. The current stable version is 2.0.0, which mandates Node.js 16 or higher and functions exclusively as an ESM-only package. While there isn't a fixed release cadence, updates typically occur as needed for features, bug fixes, or to align with evolving JavaScript standards, with major versions reserved for significant breaking changes like environment requirements or API shifts. This package is particularly valuable for projects within the unified ecosystem (unist, vfile) and integrates seamlessly with parsing tools like Acorn. It differentiates itself by providing a robust, extensible mechanism for code generation, including optional source map support and custom handlers for various AST nodes, offering a complementary utility to `esast-util-from-js` which performs the inverse operation.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to parse a JavaScript file using Acorn, then serialize its ESTree representation back into JavaScript code using `toJs`, including how to handle the `Result` object.

import fs from 'node:fs/promises';
import { parse } from 'acorn';
import { toJs } from 'estree-util-to-js';

async function serializeExample() {
  const fileContent = String(await fs.readFile('./input.js', 'utf8'));

  // Create a dummy file for the example
  await fs.writeFile('./input.js', 'export const greeting = "Hello, World!";', 'utf8');

  const tree = parse(fileContent, {
    ecmaVersion: 2022,
    sourceType: 'module',
    locations: true // Required for source maps, though not used in simple output
  });

  // @ts-expect-error: acorn's types can be complex with estree interop, but it works fine.
  const result = toJs(tree);

  console.log('Serialized JavaScript:\n', result.value);
  // console.log('Source Map (if generated):', result.map);

  // Clean up the dummy file
  await fs.unlink('./input.js');
}

serializeExample().catch(console.error);

view raw JSON →