CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-babel--parser

A JavaScript parser for modern syntax including TypeScript, Flow, and JSX

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

@babel/parser

@babel/parser (formerly babylon) is a JavaScript parser that generates an Abstract Syntax Tree (AST) from source code. It supports modern JavaScript syntax, TypeScript, Flow, and JSX through a comprehensive plugin system, making it the core parsing engine for the Babel ecosystem.

Package Information

  • Package Name: @babel/parser
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @babel/parser

Core Imports

import { parse, parseExpression } from "@babel/parser";

For CommonJS:

const { parse, parseExpression } = require("@babel/parser");

Basic Usage

import { parse, parseExpression } from "@babel/parser";

// Parse a complete JavaScript/TypeScript program
const ast = parse("const x = 42;", {
  sourceType: "module",
  plugins: ["typescript"]
});

// Parse a single expression
const expr = parseExpression("x + y", {
  plugins: ["jsx"]
});

// Parse with error recovery
const result = parse("const x = ;", {
  errorRecovery: true,
  sourceType: "module"
});
// result.errors will contain parsing errors

Architecture

@babel/parser is built around several key components:

  • Core Parser: Main parsing engine that converts source code to AST nodes
  • Plugin System: Modular architecture supporting syntax extensions (TypeScript, Flow, JSX, etc.)
  • Token System: Complete lexical analysis with token type definitions
  • Error Recovery: Optional mode for partial parsing with error collection
  • Source Map Support: Integration with source location tracking and mapping

Capabilities

Program Parsing

Parse complete JavaScript, TypeScript, or other supported source code as an entire program.

/**
 * Parse the provided code as an entire ECMAScript program
 * @param input - Source code string to parse
 * @param options - Optional parser configuration
 * @returns ParseResult containing File AST node and optional errors
 */
function parse(input: string, options?: ParserOptions): ParseResult<File>;

Expression Parsing

Parse a single JavaScript expression without requiring a complete program structure.

/**
 * Parse the provided code as a single expression
 * @param input - Source code string to parse as expression
 * @param options - Optional parser configuration
 * @returns ParseResult containing Expression AST node and optional errors
 */
function parseExpression(input: string, options?: ParserOptions): ParseResult<Expression>;

Parser Configuration

Comprehensive options for customizing parsing behavior and enabling language features.

type ParserOptions = Partial<Options>;

interface Options {
  /** Source type interpretation mode */
  sourceType?: SourceType;
  /** Allow import/export statements anywhere */
  allowImportExportEverywhere?: boolean;
  /** Allow await outside async functions */
  allowAwaitOutsideFunction?: boolean;
  /** Allow return statements at top level */
  allowReturnOutsideFunction?: boolean;
  /** Allow new.target outside functions/classes */
  allowNewTargetOutsideFunction?: boolean;
  /** Allow super outside methods */
  allowSuperOutsideMethod?: boolean;
  /** Allow exports to reference undeclared variables */
  allowUndeclaredExports?: boolean;
  /** Allow yield outside generator functions */
  allowYieldOutsideFunction?: boolean;
  /** Parse according to Annex B syntax */
  annexB?: boolean;
  /** Attach comments to AST nodes */
  attachComment?: boolean;
  /** Continue parsing after errors */
  errorRecovery?: boolean;
  /** Source filename for source maps */
  sourceFilename?: string;
  /** Starting index offset */
  startIndex?: number;
  /** Starting line number */
  startLine?: number;
  /** Starting column number */
  startColumn?: number;
  /** Array of plugins to enable */
  plugins?: Plugin[];
  /** Force strict mode parsing */
  strictMode?: boolean;
  /** Add range information to nodes */
  ranges?: boolean;
  /** Include tokens in result */
  tokens?: boolean;
  /** Create ParenthesizedExpression nodes */
  createParenthesizedExpressions?: boolean;
  /** Create ImportExpression nodes */
  createImportExpressions?: boolean;
}

type SourceType = "script" | "commonjs" | "module" | "unambiguous";

Plugin System

Extensible plugin architecture for supporting different syntax variations and language features.

type Plugin = PluginConfig;
type PluginConfig = Plugin | ParserPluginWithOptions;

type Plugin =
  | "asyncDoExpressions"
  | "asyncGenerators"
  | "bigInt"
  | "classPrivateMethods"
  | "classPrivateProperties"
  | "classProperties"
  | "classStaticBlock"
  | "decimal"
  | "decorators-legacy"
  | "deferredImportEvaluation"
  | "decoratorAutoAccessors"
  | "destructuringPrivate"
  | "deprecatedImportAssert"
  | "doExpressions"
  | "dynamicImport"
  | "explicitResourceManagement"
  | "exportDefaultFrom"
  | "exportNamespaceFrom"
  | "flow"
  | "flowComments"
  | "functionBind"
  | "functionSent"
  | "importMeta"
  | "jsx"
  | "jsonStrings"
  | "logicalAssignment"
  | "importAssertions"
  | "importReflection"
  | "moduleBlocks"
  | "moduleStringNames"
  | "nullishCoalescingOperator"
  | "numericSeparator"
  | "objectRestSpread"
  | "optionalCatchBinding"
  | "optionalChaining"
  | "partialApplication"
  | "placeholders"
  | "privateIn"
  | "regexpUnicodeSets"
  | "sourcePhaseImports"
  | "throwExpressions"
  | "topLevelAwait"
  | "v8intrinsic";

type ParserPluginWithOptions =
  | ["decorators", DecoratorsPluginOptions]
  | ["discardBinding", { syntaxType: "void" }]
  | ["estree", { classFeatures?: boolean }]
  | ["importAttributes", { deprecatedAssertSyntax: boolean }]
  | ["moduleAttributes", { version: "may-2020" }]
  | ["optionalChainingAssign", { version: "2023-07" }]
  | ["pipelineOperator", PipelineOperatorPluginOptions]
  | ["recordAndTuple", RecordAndTuplePluginOptions]
  | ["flow", FlowPluginOptions]
  | ["typescript", TypeScriptPluginOptions];

Plugin Options

Configuration interfaces for plugins that accept options.

interface DecoratorsPluginOptions {
  /** Allow decorators before export declarations */
  decoratorsBeforeExport?: boolean;
  /** Allow call syntax for decorators */
  allowCallParenthesized?: boolean;
}

interface TypeScriptPluginOptions {
  /** Parse as TypeScript declaration file */
  dts?: boolean;
  /** Disallow ambiguous JSX-like syntax */
  disallowAmbiguousJSXLike?: boolean;
}

interface FlowPluginOptions {
  /** Enable all Flow syntax features */
  all?: boolean;
  /** Enable Flow enums (Babel 8+) */
  enums?: boolean;
}

interface PipelineOperatorPluginOptions {
  /** Pipeline operator proposal to support */
  proposal: "minimal" | "fsharp" | "hack" | "smart";
  /** Topic token for pipeline operator */
  topicToken?: "%" | "#" | "@@" | "^^" | "^";
}

interface RecordAndTuplePluginOptions {
  /** Syntax style for records and tuples */
  syntaxType: "bar" | "hash";
}

Parse Results

Structured results containing AST nodes and optional error information.

type ParseResult<Result extends File | Expression = File> = Result & {
  /** Parsing errors when errorRecovery is enabled */
  errors: null | ParseError[];
};

interface ParseError {
  /** Error code identifier */
  code: string;
  /** Specific reason code for the error */
  reasonCode: string;
}

AST Node Types

Core AST node types used in parsing results (from @babel/types).

/** Root AST node representing a complete file */
interface File {
  type: "File";
  program: Program;
  comments?: Comment[];
  tokens?: Token[];
}

/** Base interface for all expression AST nodes */
interface Expression {
  type: string;
  start?: number;
  end?: number;
  loc?: SourceLocation;
}

Token System

Access to tokenization types and token information.

/** Token types used by the tokenizer */
const tokTypes: Record<string, ExportedTokenType>;

/** Individual token from tokenization */
interface Token {
  type: TokenType;
  value: any;
  start: number;
  end: number;
  loc: SourceLocation;
}

Usage Examples

TypeScript Parsing

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

const code = `
interface User {
  name: string;
  age: number;
}

const user: User = { name: "Alice", age: 30 };
`;

const ast = parse(code, {
  sourceType: "module",
  plugins: ["typescript"]
});

JSX Parsing

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

const jsxCode = `
const element = (
  <div className="container">
    <h1>Hello, {name}!</h1>
  </div>
);
`;

const ast = parse(jsxCode, {
  sourceType: "module",
  plugins: ["jsx"]
});

Flow Parsing

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

const flowCode = `
// @flow
type Person = {
  name: string,
  age: number
};

function greet(person: Person): string {
  return "Hello, " + person.name;
}
`;

const ast = parse(flowCode, {
  sourceType: "module",
  plugins: ["flow"]
});

Decorators and Advanced Features

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

const decoratorCode = `
@component
class MyComponent {
  @observable
  count = 0;

  @action
  increment() {
    this.count++;
  }
}
`;

const ast = parse(decoratorCode, {
  sourceType: "module",
  plugins: [
    ["decorators", { decoratorsBeforeExport: false }]
  ]
});

Error Recovery Mode

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

const invalidCode = `
const x = ;
function foo() {
  return
}
`;

const result = parse(invalidCode, {
  sourceType: "module",
  errorRecovery: true
});

if (result.errors) {
  console.log("Parsing errors:", result.errors);
  // Continue processing the partial AST
}

Expression Parsing

import { parseExpression } from "@babel/parser";

// Parse complex expressions
const mathExpr = parseExpression("Math.pow(x, 2) + Math.sqrt(y)");
const objectExpr = parseExpression("{ name: 'test', value: 42 }");
const functionExpr = parseExpression("(x, y) => x + y");

// Parse JSX expressions
const jsxExpr = parseExpression("<Component prop={value} />", {
  plugins: ["jsx"]
});

docs

index.md

tile.json