By default, Recast uses esprima. To support TypeScript, Flow, or Babel, you can pass a different parser in the options object.
Important: To ensure conservative reprinting works, you must call recast.parse rather than using the external parser directly. This allows Recast to create a shadow copy of the AST with .original properties.
Using a custom parser object:
const ast = recast.parse(source, {
parser: {
parse(source) {
return require("acorn").parse(source, { /* options */ });
}
}
});
Using preconfigured parsers:
Recast provides preconfigured parsers for common syntaxes. Note that you may need to manually install the underlying parser (e.g., @babel/parser or acorn) via npm.
// For TypeScript
const tsAst = recast.parse(source, {
parser: require("recast/parsers/typescript")
});
const tsAst = recast.parse(source, {
parser: require("recast/parsers/typescript")
});