Acorn with Node.js Syntax Plugins

2.0.1 · active · verified Sun Apr 19

acorn-node is a JavaScript parser library that bundles the core Acorn parser with a set of preloaded plugins, providing syntax parity with recent Node.js versions. This includes support for features like BigInt, numeric separators, public and private class fields (instance and static), dynamic `import()`, `import.meta`, and `export * as ns from`. The package sets default options like `ecmaVersion: 2019`, `allowHashBang: true`, and `allowReturnOutsideFunction: true` to align with Node.js module semantics. The current stable version is 2.0.1. Releases appear to follow Acorn's updates and Node.js syntax advancements, with minor patch releases addressing specific parsing issues. Its key differentiator is providing a ready-to-use Acorn instance capable of parsing modern Node.js JavaScript without requiring manual plugin configuration, including compatibility for older Node.js versions via Bublé-compiled plugins.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates parsing a JavaScript code snippet using acorn-node, including modern features like private class fields, static class fields, numeric separators, BigInts, dynamic `import()`, and `export * as ns from`. It then uses the bundled `walk` utility to traverse the AST and identify specific node types.

import * as acorn from 'acorn-node';
import { simple as walkSimple } from 'acorn-node/walk';

const code = `
  class MyClass {
    #privateField = 1;
    static publicStaticField = 2;
    constructor() {
      console.log(this.#privateField);
    }
  }
  const bigNum = 1_000_000_000_000_000n;
  const dynamicImport = import('./module.js');
  export * as ns from './ns.mjs';
`;

try {
  const ast = acorn.parse(code, { sourceType: 'module' });
  console.log('AST parsed successfully. Root node type:', ast.type);

  let foundClassFields = 0;
  walkSimple(ast, {
    PropertyDefinition(node) {
      if (node.key.type === 'PrivateIdentifier' || node.static) {
        foundClassFields++;
      }
    },
    ImportExpression(node) {
      console.log('Found dynamic import:', node.source.value);
    }
  });
  console.log(`Found ${foundClassFields} class field definitions.`);

} catch (e) {
  console.error('Parsing error:', e.message);
}

view raw JSON →