A JavaScript parser used in Babel for parsing ECMAScript code with support for JSX, Flow, and experimental language features
npx @tessl/cli install tessl/npm-babylon@6.11.0Babylon 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.
npm install babylonconst babylon = require('babylon');
const ast = babylon.parse(code);ES Modules:
import { parse } from 'babylon';
const ast = parse(code);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']
});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 parseoptions (object, optional): Parser configuration optionsReturns: AST object with Program node as root
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[];
}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']
});The root node of every AST.
interface Program {
type: "Program";
body: Statement[];
sourceType: "script" | "module";
loc?: SourceLocation;
range?: [number, number];
}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
}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}`);
}
}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 }// 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'
});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;
}, {});Babylon serves as the foundation parser for the Babel ecosystem:
// 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);