Documentation

Complete guide to using the Esprima parser

Installation

Install Esprima using npm or yarn:

npm install esprima
yarn add esprima

Basic Usage

Import and use Esprima to parse JavaScript code:

import * as esprima from 'esprima';

const code = 'const answer = 42';
const ast = esprima.parseScript(code);

console.log(JSON.stringify(ast, null, 2));

This will output the Abstract Syntax Tree representation of your JavaScript code.

API Reference

parseScript(code, options?)

Parses JavaScript code as a script (not a module).

Parameters:

  • code (string): The JavaScript code to parse
  • options (object, optional): Parser configuration options

Returns:

An AST object representing the parsed code

parseModule(code, options?)

Parses JavaScript code as an ES6 module.

Parameters:

  • code (string): The JavaScript module code to parse
  • options (object, optional): Parser configuration options

Returns:

An AST object representing the parsed module

tokenize(code, options?)

Tokenizes JavaScript code without building the full AST.

Parameters:

  • code (string): The JavaScript code to tokenize
  • options (object, optional): Tokenizer options

Returns:

An array of token objects

Parser Options

Customize the parser behavior with these options:

range

Type: boolean

Default: false

Include start and end positions for each node

loc

Type: boolean

Default: false

Include line and column location for each node

tokens

Type: boolean

Default: false

Collect tokens in the output

comment

Type: boolean

Default: false

Collect comments in the output

jsx

Type: boolean

Default: false

Enable JSX syntax support

tolerant

Type: boolean

Default: false

Continue parsing after errors

Example with Options

const ast = esprima.parseScript(code, {
  range: true,
  loc: true,
  tokens: true,
  comment: true
});

Understanding AST

The Abstract Syntax Tree (AST) is a tree representation of your code's structure. Each node in the tree represents a construct in your code.

Common Node Types

Program

The root node of every AST, containing all top-level statements

VariableDeclaration

Variable declarations (const, let, var)

FunctionDeclaration

Function declarations and expressions

CallExpression

Function and method calls

BinaryExpression

Binary operations like +, -, *, /

Identifier

Variable and function names

Example AST Structure

// Code: const x = 5;

{
  "type": "Program",
  "body": [{
    "type": "VariableDeclaration",
    "declarations": [{
      "type": "VariableDeclarator",
      "id": {
        "type": "Identifier",
        "name": "x"
      },
      "init": {
        "type": "Literal",
        "value": 5
      }
    }],
    "kind": "const"
  }]
}

Error Handling

Esprima throws errors when it encounters invalid JavaScript syntax. Always wrap parsing in try-catch blocks:

try {
  const ast = esprima.parseScript(code);
  // Process the AST
} catch (error) {
  console.error('Parse error:', error.message);
  // Error includes line, column, and description
}

Error Properties

  • message: Human-readable error description
  • lineNumber: Line where the error occurred
  • column: Column where the error occurred
  • description: Detailed error information

Additional Resources