Babel Parser (formerly Babylon)

6.18.0 · renamed · verified Sun Apr 19

Babel Parser, previously known as Babylon, is a highly configurable JavaScript parser that generates an Abstract Syntax Tree (AST) from source code. It is a fundamental component of the Babel toolchain, used for transpiling modern JavaScript into compatible versions. Currently stable at version 7.x, it receives frequent updates, including beta releases for upcoming ECMAScript features. Its key differentiators include a pluggable architecture supporting a wide array of experimental and standard JavaScript syntax extensions like JSX, Flow, and TypeScript, as well as new proposals like nullish coalescing, optional chaining, and the pipeline operator. The parser offers both `parse` for full programs and `parseExpression` for single expressions, along with options for comment attachment and error recovery, providing detailed AST output based on the ESTree spec with Babel's specific deviations.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing a TypeScript and JSX mixed-syntax code snippet into an AST, enabling the necessary plugins for correct parsing.

import { parse } from '@babel/parser';

const code = `
  function greet(name: string): string {
    const message = `Hello, ${name}!!`;
    return <p>{message}</p>;
  }

  const result = greet('World');
  console.log(result);
`;

try {
  const ast = parse(code, {
    sourceType: 'module',
    plugins: ['typescript', 'jsx']
  });
  console.log('Successfully parsed AST:');
  // A simplified log to show the top-level structure, 
  // the full AST can be very large.
  console.log(JSON.stringify(ast.program.body[0], null, 2));
  console.log('...');

  // Example of accessing a node
  const functionDeclaration = ast.program.body[0];
  if (functionDeclaration.type === 'FunctionDeclaration') {
    console.log(`Function name: ${functionDeclaration.id.name}`);
  }

} catch (error) {
  console.error('Parsing failed:', error.message);
}

view raw JSON →