Acorn JavaScript Parser

8.16.0 · active · verified Tue Apr 21

Acorn is a compact, high-performance JavaScript parser implemented entirely in JavaScript. It parses ECMAScript code into an Abstract Syntax Tree (AST) that conforms to the ESTree specification. The current stable version is 8.16.0, as of February 2026, with frequent releases to support the latest ECMAScript features and bug fixes. Acorn differentiates itself by its minimal footprint and speed, serving as a fundamental component in many JavaScript tooling projects, including linters (like ESLint), bundlers, and transpilers. It strictly implements 'stage 4' (finalized) ECMAScript features, requiring plugins for experimental syntax.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates parsing a JavaScript code snippet using Acorn, specifying ECMAScript version and source type, and then logging the generated AST and handling potential syntax errors.

import { parse } from 'acorn';

const code = `
  function greet(name = 'World') {
    console.log(`Hello, ${name}!`);
  }
  greet('Registry');
  greet();
`;

try {
  const ast = parse(code, {
    ecmaVersion: 2022, // Specify the ECMAScript version
    sourceType: 'module', // Or 'script', or 'commonjs'
    locations: true, // Attach line/column location info to nodes
  });
  console.log('AST generated successfully:');
  console.log(JSON.stringify(ast, null, 2));

  // Example of accessing a node
  if (ast.body[0].type === 'FunctionDeclaration') {
    console.log(`\nFirst function name: ${ast.body[0].id.name}`);
  }
} catch (error) {
  console.error('Parsing error:', error.message);
  console.error('Position:', error.pos, 'Line:', error.loc.line, 'Column:', error.loc.column);
}

view raw JSON →