Primary parsing functionality that converts JavaScript/Flow/JSX source code into Abstract Syntax Trees with comprehensive configuration options.
Main entry point for parsing JavaScript, Flow, and JSX code into AST structures.
/**
* Parse JavaScript/Flow/JSX source code into an AST
* @param code - Source code string to parse
* @param options - Optional parsing configuration
* @returns ESTree Program node or Babel File object
*/
function parse(code: string, options?: ParserOptions): Program;
/**
* Parse JavaScript source code into Babel-compatible AST
* @param code - Source code string to parse
* @param options - Parsing configuration with babel: true
* @returns Babel File object containing Program and metadata
*/
function parse(code: string, options: {...ParserOptions, babel: true}): BabelFile;
interface BabelFile {
type: "File";
program: Program;
comments?: Comment[];
tokens?: Token[];
}Usage Examples:
import { parse } from "hermes-parser";
// Basic parsing (ESTree format)
const ast = parse("const x = 1;");
console.log(ast.type); // "Program"
// Parse with Flow type annotations
const flowCode = `
function add(x: number, y: number): number {
return x + y;
}
`;
const flowAst = parse(flowCode, { flow: "all" });
// Parse JSX code
const jsxCode = `
const component = <div className="container">
<h1>Hello {name}</h1>
</div>;
`;
const jsxAst = parse(jsxCode);
// Get Babel-compatible AST
const babelAst = parse("const x = 1;", { babel: true });
console.log(babelAst.type); // "File"
console.log(babelAst.program.type); // "Program"Control parsing behavior through the ParserOptions interface.
interface ParserOptions {
/** Allow return statements outside of functions */
allowReturnOutsideFunction?: boolean;
/** Output Babel-compatible AST format instead of ESTree */
babel?: boolean;
/** Flow syntax parsing mode */
flow?: "all" | "detect";
/** Enable experimental React component syntax */
enableExperimentalComponentSyntax?: boolean;
/** Enable experimental Flow match syntax */
enableExperimentalFlowMatchSyntax?: boolean;
/** Target React runtime version for transformations */
reactRuntimeTarget?: "18" | "19";
/** Filename for source locations in AST nodes */
sourceFilename?: string;
/** Module type for parsing behavior */
sourceType?: "module" | "script" | "unambiguous";
/** Include token array in output AST */
tokens?: boolean;
}
/** Set of valid ParserOptions property names */
const ParserOptionsKeys: ReadonlySet<keyof ParserOptions>;Configuration Examples:
// Parse with all Flow features enabled
const flowAst = parse(source, {
flow: "all", // Parse all Flow syntax regardless of pragma
sourceFilename: "example.js"
});
// Parse with Flow pragma detection
const pragmaAst = parse(source, {
flow: "detect", // Only parse Flow if @flow pragma present
sourceType: "module"
});
// Parse for Babel with tokens and experimental features
const fullAst = parse(source, {
babel: true,
tokens: true,
enableExperimentalComponentSyntax: true,
enableExperimentalFlowMatchSyntax: true
});
// Parse with specific module type
const scriptAst = parse(source, {
sourceType: "script", // Treat as script, not module
allowReturnOutsideFunction: true
});Control how Flow type annotations are parsed.
Flow Detection Mode ("detect"):
@flowfoo<T>(x)Flow All Mode ("all"):
@flow// Without @flow pragma, parsed as two comparisons
const ast1 = parse("foo<T>(x)", { flow: "detect" });
// With @flow pragma, parsed as generic call expression
const ast2 = parse("// @flow\nfoo<T>(x)", { flow: "detect" });
// Always parsed as generic call expression
const ast3 = parse("foo<T>(x)", { flow: "all" });Control how the parser interprets the source code context.
Module ("module"):
Script ("script"):
Unambiguous ("unambiguous"):
// Force module parsing
const moduleAst = parse("export const x = 1;", {
sourceType: "module"
});
// Force script parsing
const scriptAst = parse("var x = 1;", {
sourceType: "script"
});
// Auto-detect based on content
const autoAst = parse("import x from 'module';", {
sourceType: "unambiguous" // Will detect as "module"
});Parse errors are thrown as enhanced SyntaxError instances with location information.
interface ParseError extends SyntaxError {
loc: {
line: number;
column: number;
};
}Error Handling Examples:
try {
const ast = parse("const = 1;"); // Invalid syntax
} catch (error) {
if (error instanceof SyntaxError) {
console.log(error.message); // "'identifier' expected in declaration"
console.log(error.loc.line); // 1
console.log(error.loc.column); // 6
}
}The parser supports two primary AST formats:
ESTree Format (Default):
rangelocBabel Format:
startend