@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.
npm install @babel/parserimport { parse, parseExpression } from "@babel/parser";For CommonJS:
const { parse, parseExpression } = require("@babel/parser");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@babel/parser is built around several key components:
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>;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>;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";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];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";
}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;
}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;
}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;
}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"]
});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"]
});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"]
});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 }]
]
});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
}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"]
});