Espree JavaScript Parser

11.2.0 · active · verified Sun Apr 19

Espree is a high-performance, Esprima-compatible JavaScript parser built upon the modular Acorn parsing library. It is the default parser used by ESLint and is designed to produce Abstract Syntax Trees (ASTs) that are highly consistent with the Esprima API, making it a drop-in replacement in many scenarios. The package is currently at stable version 11.2.0 and receives active maintenance with frequent updates, typically on a monthly or bi-monthly schedule for minor and patch releases. Key differentiators include its robust support for all modern ECMAScript features up to ES2026 (ECMAScript 17), comprehensive parsing options for fine-grained control over AST output (including ranges, locations, comments, and tokens), and official TypeScript type definitions since v11.1.0, enhancing developer experience for TypeScript projects.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing JavaScript code into an AST and extracting tokens and comments using various options, including `ecmaVersion: 'latest'` and `sourceType: 'module'`.

import * as espree from "espree";

const code = `
  // This is a comment
  function greet(name: string) {
    console.log(`Hello, ${name}!`);
  }
  greet("World");
`;

try {
  // Parse with options for range, location, comments, and tokens
  const ast = espree.parse(code, {
    ecmaVersion: "latest", // Use the latest supported ECMAScript version
    sourceType: "module",  // Or "script"
    range: true,           // Include start/end indices for each node
    loc: true,             // Include line/column for each node
    comment: true,         // Include comments in the AST
    tokens: true           // Include tokens in the AST
  });

  console.log("--- AST (truncated) ---");
  // Only log a portion for brevity, the full AST can be very large
  console.log(JSON.stringify(ast.body.slice(0, 1), null, 2));

  console.log("\n--- First 3 Tokens ---");
  if (ast.tokens) {
    ast.tokens.slice(0, 3).forEach(token => console.log(token));
  } else {
    console.log("Tokens not generated. Ensure 'tokens: true' option is set.");
  }

  console.log("\n--- Comments ---");
  if (ast.comments) {
    ast.comments.forEach(comment => console.log(comment));
  } else {
    console.log("Comments not generated. Ensure 'comment: true' option is set.");
  }

} catch (e: any) {
  console.error("Error parsing code:", e.message);
}

view raw JSON →