Parse JavaScript to ESAST/ESTree
esast-util-from-js is a utility within the unified ecosystem designed to parse JavaScript code strings into an esast syntax tree, which is an extension of the ESTree format. It integrates seamlessly with `unist` and `vfile` for processing abstract syntax trees in a structured manner. The current stable version is 2.0.1, with major releases occurring periodically to update Node.js compatibility and internal dependencies. It differentiates itself from raw `acorn` usage by providing a higher-level abstraction suitable for unified processing pipelines, making it ideal for linters, formatters, and other tools that operate on ASTs alongside other types of content. The library primarily focuses on converting serialised JavaScript into its programmatic representation, offering options for specifying JS version, module type, and other parsing rules.
Common errors
-
ERR_REQUIRE_ESM
cause Attempting to use `require()` to import `esast-util-from-js` in a CommonJS environment, but the package is ESM only.fixChange your import statement from `const { fromJs } = require('esast-util-from-js')` to `import { fromJs } from 'esast-util-from-js'`. Ensure your project is set up for ES Modules (e.g., `"type": "module"` in `package.json` or using `.mjs` file extensions). -
SyntaxError: Unexpected token (at X:Y)
cause The input JavaScript contains syntax not supported by the specified (or default) `version` option for `acorn`.fixIf using modern JavaScript features, try explicitly setting the `version` option to a newer year (e.g., `{ version: 2023 }`). If it's genuinely malformed JavaScript, correct the syntax errors in your input code. -
Error: A `VFileMessage` was thrown
cause The input JavaScript is invalid or cannot be parsed by `acorn` for other reasons, leading to a parsing error wrapped in a `VFileMessage`.fixInspect the detailed error message within the `VFileMessage` for specifics. This often indicates malformed syntax, missing plugins for non-standard syntax (like JSX), or an incorrect `module` option for the source code type (e.g., parsing ESM as a script).
Warnings
- breaking Version 2.0.0 of `esast-util-from-js` requires Node.js 16 or higher. Older Node.js versions are no longer supported.
- breaking The package now exclusively uses ES Modules (ESM) and provides an `exports` field in its `package.json`. Direct access to private APIs or CJS `require()` will fail.
- breaking `Buffer` is replaced with `Uint8Array` in the internal API and possibly in types for input `Value` (though `string` is also accepted).
- gotcha Using `version: 'latest'` in the options for `fromJs` is a sliding target. It will default to the newest supported ECMAScript year, which can be considered a breaking change across minor versions of `esast-util-from-js`.
Install
-
npm install esast-util-from-js -
yarn add esast-util-from-js -
pnpm add esast-util-from-js
Imports
- fromJs
const fromJs = require('esast-util-from-js')import { fromJs } from 'esast-util-from-js' - Options
import type { Options } from 'esast-util-from-js' - Value
import type { Value } from 'esast-util-from-js'
Quickstart
import fs from 'node:fs/promises'
import { fromJs } from 'esast-util-from-js'
const exampleCode = `
import { someFunction } from './utils.js';
const message = 'Hello, esast!';
console.log(message, someFunction());
`;
async function parseCode() {
// In a real application, you might read from a file
// const tree = fromJs(await fs.readFile('example.js', 'utf8'), { module: true });
const tree = fromJs(exampleCode, { module: true, version: 2023 });
console.log('Parsed AST (partial):');
console.log(JSON.stringify(tree, null, 2).slice(0, 500) + '...');
console.log('\nRoot type:', tree.type);
console.log('Source type:', tree.sourceType);
console.log('Number of body nodes:', tree.body.length);
}
parseCode().catch(console.error);