Parse JavaScript to ESAST/ESTree

2.0.1 · active · verified Sun Apr 19

esast-util-from-js is a utility within the unified ecosystem designed to parse JavaScript code strings into an esast syntax tree, which is an extension of the ESTree format. It integrates seamlessly with `unist` and `vfile` for processing abstract syntax trees in a structured manner. The current stable version is 2.0.1, with major releases occurring periodically to update Node.js compatibility and internal dependencies. It differentiates itself from raw `acorn` usage by providing a higher-level abstraction suitable for unified processing pipelines, making it ideal for linters, formatters, and other tools that operate on ASTs alongside other types of content. The library primarily focuses on converting serialised JavaScript into its programmatic representation, offering options for specifying JS version, module type, and other parsing rules.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to parse a JavaScript string into an esast syntax tree, specifying it as a module and a specific ES version, then logs key properties of the resulting AST.

import fs from 'node:fs/promises'
import { fromJs } from 'esast-util-from-js'

const exampleCode = `
  import { someFunction } from './utils.js';
  const message = 'Hello, esast!';
  console.log(message, someFunction());
`;

async function parseCode() {
  // In a real application, you might read from a file
  // const tree = fromJs(await fs.readFile('example.js', 'utf8'), { module: true });
  const tree = fromJs(exampleCode, { module: true, version: 2023 });
  console.log('Parsed AST (partial):');
  console.log(JSON.stringify(tree, null, 2).slice(0, 500) + '...');
  console.log('\nRoot type:', tree.type);
  console.log('Source type:', tree.sourceType);
  console.log('Number of body nodes:', tree.body.length);
}

parseCode().catch(console.error);

view raw JSON →