or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-babylon

A JavaScript parser used in Babel for parsing ECMAScript code with support for JSX, Flow, and experimental language features

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/babylon@6.11.x

To install, run

npx @tessl/cli install tessl/npm-babylon@6.11.0

index.mddocs/

Babylon

Babylon is a JavaScript parser used by Babel for parsing ECMAScript code with support for JSX, Flow, and experimental language features. It converts JavaScript source code into Abstract Syntax Trees (ASTs) that can be transformed and analyzed by other tools.

Package Information

  • Package Name: babylon
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install babylon

Core Imports

const babylon = require('babylon');
const ast = babylon.parse(code);

ES Modules:

import { parse } from 'babylon';
const ast = parse(code);

Basic Usage

const babylon = require('babylon');

// Basic parsing
const code = 'const x = 1;';
const ast = babylon.parse(code);

// Parsing with options
const ast = babylon.parse(code, {
  sourceType: 'module',
  plugins: ['jsx', 'flow']
});

// Parsing JSX
const jsxCode = 'const element = <div>Hello World</div>;';
const jsxAst = babylon.parse(jsxCode, {
  plugins: ['jsx']
});

Capabilities

Parse Function

Parses JavaScript source code and returns an Abstract Syntax Tree (AST).

/**
 * Parse JavaScript source code into an AST
 * @param {string} code - The JavaScript source code to parse
 * @param {Object} options - Parser configuration options
 * @returns {Object} AST object representing the parsed code
 */
function parse(code, options);

Parameters:

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

Returns: AST object with Program node as root

Parser Options

Configuration options for controlling parsing behavior.

interface ParserOptions {
  /** Indicates how the code should be parsed: "script" or "module" */
  sourceType?: "script" | "module";
  
  /** Allow import and export declarations anywhere */
  allowImportExportEverywhere?: boolean;
  
  /** Allow return statements outside functions */
  allowReturnOutsideFunction?: boolean;
  
  /** Parse in strict mode */
  strictMode?: boolean;
  
  /** Add range information to each node */
  ranges?: boolean;
  
  /** Add location information to each node */
  locations?: boolean;
  
  /** Filename for source maps and error reporting */
  sourceFilename?: string;
  
  /** Alias for sourceFilename */
  filename?: string;
  
  /** Array of parser plugins to enable */
  plugins?: string[];
}

Available Plugins

Parser plugins extend babylon's syntax support.

type PluginName = 
  | "jsx"                    // JSX syntax support
  | "flow"                   // Flow type annotations
  | "decorators"             // Decorator syntax
  | "asyncFunctions"         // Async/await syntax
  | "asyncGenerators"        // Async generator functions
  | "functionBind"           // Function bind operator
  | "exportExtensions"       // Export extensions
  | "exportDefaultFrom"      // Export default from
  | "objectRestSpread"       // Object rest/spread properties
  | "functionSent"           // Function.sent syntax
  | "dynamicImport"          // Dynamic import() syntax
  | "doExpressions"          // Do expressions
  | "decorators-legacy"      // Legacy decorator syntax
  | "classProperties"        // Class property syntax
  | "trailingFunctionCommas" // Trailing commas in function parameters;

Usage Examples:

// Enable JSX and Flow support
const ast = babylon.parse(code, {
  plugins: ['jsx', 'flow']
});

// Enable experimental features
const ast = babylon.parse(code, {
  plugins: ['asyncFunctions', 'objectRestSpread', 'dynamicImport']
});

AST Structure

Program Node

The root node of every AST.

interface Program {
  type: "Program";
  body: Statement[];
  sourceType: "script" | "module";
  loc?: SourceLocation;
  range?: [number, number];
}

Node Properties

All AST nodes contain common properties.

interface BaseNode {
  /** The node type identifier */
  type: string;
  
  /** Location information with start/end positions */
  loc?: SourceLocation;
  
  /** Start and end character indices */
  range?: [number, number];
}

interface SourceLocation {
  start: Position;
  end: Position;
  filename?: string;
}

interface Position {
  line: number;    // 1-indexed
  column: number;  // 0-indexed
}

Error Handling

SyntaxError

Thrown when parsing fails due to syntax errors.

class SyntaxError extends Error {
  /** Error description */
  message: string;
  
  /** Location of the error in the source */
  loc: Position;
  
  /** Character position of the error */
  pos: number;
}

Usage Example:

try {
  const ast = babylon.parse('const x ='); // Invalid syntax
} catch (error) {
  if (error instanceof SyntaxError) {
    console.log(`Parse error at line ${error.loc.line}: ${error.message}`);
  }
}

Advanced Usage

Parsing with Source Information

const code = 'const x = 1;';
const ast = babylon.parse(code, {
  sourceFilename: 'example.js',
  locations: true,
  ranges: true
});

// Each node will have location information
console.log(ast.body[0].loc.start); // { line: 1, column: 0 }

Module vs Script Parsing

// Parse as ES module (allows import/export)
const moduleAst = babylon.parse(importCode, {
  sourceType: 'module'
});

// Parse as script (traditional JavaScript)
const scriptAst = babylon.parse(scriptCode, {
  sourceType: 'script'
});

Multiple File Parsing

const files = {
  'a.js': 'const a = 1;',
  'b.js': 'const b = 2;'
};

const asts = Object.keys(files).reduce((parsed, filename) => {
  parsed[filename] = babylon.parse(files[filename], {
    sourceFilename: filename
  });
  return parsed;
}, {});

Integration with Babel Ecosystem

Babylon serves as the foundation parser for the Babel ecosystem:

  • babel-generator: Converts babylon ASTs back to code
  • babel-traverse: Traverses and modifies babylon ASTs
  • babel-types: Provides utilities for working with babylon AST nodes
  • babel-core: Uses babylon as the default parser
// Typical Babel workflow with babylon
const babylon = require('babylon');
const generate = require('babel-generator').default;
const traverse = require('babel-traverse').default;

// Parse
const ast = babylon.parse('const x = 1;');

// Transform
traverse(ast, {
  // visitor methods
});

// Generate
const output = generate(ast);