See usage instructions.
See https://stackblitz.com/edit/oxc-parser for usage example.
When parsing JS or JSX files, the AST returned is fully conformant with the ESTree standard, the same as produced by Acorn.
When parsing TypeScript, the AST conforms to @typescript-eslint/typescript-estree's TS-ESTree format.
If you need all ASTs in the same with-TS-properties format, use the astType: 'ts' option.
The only differences between Oxc's AST and ESTree / TS-ESTree are:
- Support for Stage 3 decorators.
- Support for the Stage 3 ECMA feature
import source. - Addition of a non-standard
hashbangfield toProgram. - Non-standard
ParenthesizedExpressionandTSParenthesizedTypenodes whenpreserveParensis enabled (the default). SetpreserveParens: falseto omit them.
That aside, the AST should completely align with Acorn's ESTree AST or TS-ESLint's TS-ESTree. Any deviation would be considered a bug.
ESTree and TS-ESTree do not define an order for node properties. oxc-parser emits them in this
order:
type.- Node-specific fields in Oxc's defined serialization order. Properties containing child nodes
have the same relative order as the entries in
visitorKeys[node.type]. start, thenend.range, when therangeoption is enabled.
visitorKeys is an exported map from a node type to the properties containing that node's children,
in traversal order. For example, visitorKeys.ConditionalExpression is
['test', 'consequent', 'alternate']. This is not alphabetical order: walking alternate before
test would not match the syntax or evaluation order of a conditional expression.
Fields omitted by the selected astType do not change the relative order of the remaining fields.
A generic walker which recursively inspects Object.keys(node) therefore visits standard ESTree
children in the same relative order as Oxc's Visitor and the exported visitorKeys.
@oxc-project/types can be used. For example:
import { Statement } from "@oxc-project/types";An AST visitor is provided. See example below.
This package also exports visitor keys which can be used with any other ESTree walker.
import { visitorKeys } from "oxc-parser";By default, Oxc parser does not produce semantic errors where symbols and scopes are needed.
To enable semantic errors, apply the option showSemanticErrors: true.
For example,
let foo;
let foo;Does not produce any errors when showSemanticErrors is false, which is the default behavior.
Fast mode is best suited for parser plugins, where other parts of your build pipeline has already checked for errors.
Please note that turning off fast mode incurs a small performance overhead.
It is likely that you are writing a parser plugin that requires ESM information.
To avoid walking the AST again, Oxc Parser returns ESM information directly.
This information can be used to rewrite import and exports with the help of magic-string,
without any AST manipulations.
export interface EcmaScriptModule {
/**
* Has ESM syntax.
*
* i.e. `import` and `export` statements, and `import.meta`.
*
* Dynamic imports `import('foo')` are ignored since they can be used in non-ESM files.
*/
hasModuleSyntax: boolean;
/** Import statements */
staticImports: Array<StaticImport>;
/** Export statements */
staticExports: Array<StaticExport>;
/** Dynamic import expressions */
dynamicImports: Array<DynamicImport>;
/** Span positions of `import.meta` */
importMetas: Array<Span>;
}// Synchronous parsing
parseSync(filename: string, sourceText: string, options?: ParserOptions): ParseResult
// Asynchronous parsing
parse(filename: string, sourceText: string, options?: ParserOptions): Promise<ParseResult>Prefer parseSync for most workloads. parse moves Rust parsing to a worker-pool thread,
but AST deserialization still runs synchronously on the calling thread and usually accounts
for most of the work. To parse multiple files in parallel, use parseSync in worker threads.
import { parseSync, Visitor } from "oxc-parser";
const code = "const url: String = /* 🤨 */ import.meta.url;";
// File extension is used to determine which dialect to parse source as.
const filename = "test.tsx";
const result = parseSync(filename, code);
// Or use async version: const result = await parse(filename, code);
// An array of errors, if any.
console.log(result.errors);
// AST and comments.
console.log(result.program, result.comments);
// ESM information - imports, exports, `import.meta`s.
console.log(result.module);
// Visit the AST
const visitations = [];
const visitor = new Visitor({
VariableDeclaration(decl) {
visitations.push(`enter ${decl.kind}`);
},
"VariableDeclaration:exit"(decl) {
visitations.push(`exit ${decl.kind}`);
},
Identifier(ident) {
visitations.push(ident.name);
},
});
visitor.visit(result.program);
// Logs: [ 'enter const', 'url', 'String', 'import', 'meta', 'url', 'exit const' ]
console.log(visitations);All options are optional.
lang:'js'|'jsx'|'ts'|'tsx'|'dts'. Set language of source. If omitted, language is deduced from file extension.sourceType:'script'|'module'|'commonjs'|'unambiguous'. Override the module kind. When bothsourceTypeandlangare omitted,.mjs/.mtsuse module mode,.cjs/.ctsuse CommonJS mode, and.js/.jsx/.ts/.tsxuse unambiguous mode. An explicitlanguses unambiguous mode, except'dts', which uses module mode. An explicitsourceTypetakes precedence.astType:'js'|'ts'. Set to'ts'if you want ASTs of plain JS/JSX files to contain TypeScript-specific properties.range:true|false. Iftrue, AST nodes contain arangefield. Defaults tofalse.preserveParens:true|false. Iftrue, parenthesized expressions are represented by (non-standard)ParenthesizedExpressionandTSParenthesizedTypeAST nodes. Defaults totrue.showSemanticErrors:true|false. Iftrue, check file for semantic errors which parser does not otherwise emit e.g.let x; let x;. Has a small performance cost. Defaults tofalse.