Babel Parser (formerly Babylon)
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
-
SyntaxError: Unexpected token
cause The parser encountered syntax it does not recognize, usually because a required plugin for a non-standard feature (e.g., JSX, TypeScript) was not enabled in the options, or there is an actual syntax error in the code.fixEnable the appropriate plugin(s) in the `plugins` array within the parser options (e.g., `plugins: ['jsx', 'typescript']`) or review your code for genuine syntax errors. Check the `sourceType` option if dealing with modules. -
ReferenceError: require is not defined
cause This error typically occurs when attempting to use CommonJS `require()` in an ES Module environment, or when running `@babel/parser` code (which is primarily ESM) directly in an environment that doesn't support ES Modules (like older Node.js versions without transpilation or specific flags) or expects a CommonJS export from the deprecated `babylon` package.fixIf using `@babel/parser` (v7+), prefer ES Module `import` syntax: `import { parse } from '@babel/parser';`. Ensure your environment supports ES Modules (e.g., Node.js 14+ or configure Babel/Webpack for transpilation). If targeting older Node, consider using a CommonJS wrapper or transpiling your parsing script. -
Parsing error: Cannot find module '@babel/preset-env'
cause This error often arises in build tools like ESLint when they attempt to use `@babel/parser` via a configuration that expects Babel presets to be available during parsing, but they are either missing or the environment is misconfigured (e.g., monorepo setup, wrong working directory).fixEnsure `@babel/preset-env` (and any other necessary presets) are installed and correctly configured in your project's Babel configuration files (e.g., `babel.config.js`, `.babelrc`). If it's an ESLint-specific issue in an IDE, adjust ESLint working directories or ensure ESLint's parser is correctly configured, typically to `@babel/eslint-parser` which then uses `@babel/parser` internally.
Warnings
- breaking The `babylon` npm package was officially renamed to `@babel/parser` with the release of Babel 7. Projects should migrate to the `@babel/parser` package to receive updates and align with the Babel ecosystem. The `babylon` package is no longer maintained.
- breaking Babel 7, which includes `@babel/parser`, dropped support for older Node.js versions, specifically 0.10, 0.12, 4, and 5. Ensure your environment uses a supported Node.js version (typically Node.js 6+ at the time of Babel 7's release, now much higher).
- breaking The AST format has undergone several breaking changes between Babylon 6 and `@babel/parser` 7. Notable changes include `PrivateName.name` being renamed to `.id` (v7.0.0-beta.22) and clearer separation of Flow and TypeScript specific AST node types (v7.0.0-beta.25).
- gotcha By default, `@babel/parser` only supports standard ECMAScript syntax. Parsing non-standard features like JSX, Flow, TypeScript, or experimental language proposals requires explicitly enabling the corresponding plugins in the parser options. Failing to do so will result in a `SyntaxError: Unexpected token`.
- gotcha The default `sourceType` for parsing is 'script'. For code containing ES Modules (`import`/`export` statements), you must set `sourceType: 'module'` in the parser options. Incorrect `sourceType` can lead to parsing errors or unexpected behavior.
Install
-
npm install babylon -
yarn add babylon -
pnpm add babylon
Imports
- parse
const parse = require('babylon').parse;import { parse } from '@babel/parser'; - parseExpression
import { parseExpression } from 'babylon';import { parseExpression } from '@babel/parser'; - ParserOptions
import { ParserOptions } from '@babel/parser';import type { ParserOptions } from '@babel/parser';
Quickstart
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);
}