Convert Figma logo to code with AI

acornjs logoacorn

A small, fast, JavaScript-based JavaScript parser

10,469
867
10,469
13

Top Related Projects

43,160

🐠 Babel is a compiler for writing next generation JavaScript.

2,275

Monorepo for the JS language tools.

5,093

The ESTree Spec

8,615

🗜 JavaScript parser, mangler and compressor toolkit for ES6+

30,914

Rust-based platform for the Web

Quick Overview

Acorn is a small, fast JavaScript parser written in JavaScript. It is fully compatible with the ECMAScript 2020 specification and can be used to parse JavaScript code into an Abstract Syntax Tree (AST). Acorn is designed to be both efficient and flexible, making it suitable for various applications, including code analysis, transformation, and generation.

Pros

  • Lightweight and fast performance
  • Highly extensible through plugins
  • Supports the latest ECMAScript features
  • Well-documented and actively maintained

Cons

  • Limited to JavaScript parsing only
  • Requires additional libraries for advanced AST manipulation
  • May have a steeper learning curve for beginners
  • Not as feature-rich as some larger parsing libraries

Code Examples

  1. Parsing a simple JavaScript expression:
import * as acorn from "acorn";

const ast = acorn.parse("const x = 42;", { ecmaVersion: 2020 });
console.log(JSON.stringify(ast, null, 2));
  1. Using a custom parser with plugins:
import { Parser } from "acorn";
import jsx from "acorn-jsx";

const JSXParser = Parser.extend(jsx());
const ast = JSXParser.parse("<div>Hello, world!</div>", {
  ecmaVersion: 2020,
});
console.log(JSON.stringify(ast, null, 2));
  1. Tokenizing JavaScript code:
import * as acorn from "acorn";

const tokens = acorn.tokenizer("let y = x + 5;", { ecmaVersion: 2020 });
for (const token of tokens) {
  console.log(token.type.label, token.value);
}

Getting Started

To use Acorn in your project, follow these steps:

  1. Install Acorn using npm:

    npm install acorn
    
  2. Import Acorn in your JavaScript file:

    import * as acorn from "acorn";
    
  3. Parse JavaScript code:

    const ast = acorn.parse("const z = 10;", { ecmaVersion: 2020 });
    console.log(JSON.stringify(ast, null, 2));
    

This will output the AST representation of the parsed JavaScript code. You can then use this AST for further analysis or manipulation.

Competitor Comparisons

43,160

🐠 Babel is a compiler for writing next generation JavaScript.

Pros of Babel

  • More comprehensive JavaScript transformation capabilities, including transpilation and polyfilling
  • Extensive plugin ecosystem for customizing transformations
  • Supports the latest ECMAScript features and proposals

Cons of Babel

  • Larger codebase and slower parsing compared to Acorn
  • More complex configuration and setup process
  • Higher memory usage and longer build times for large projects

Code Comparison

Acorn (parsing):

import * as acorn from "acorn";
const ast = acorn.parse("const x = 42;", {ecmaVersion: 2020});

Babel (parsing and transforming):

import * as babel from "@babel/core";
const result = babel.transform("const x = 42;", {
  presets: ["@babel/preset-env"]
});
console.log(result.code);

Acorn focuses on parsing JavaScript into an Abstract Syntax Tree (AST), while Babel provides a full suite of tools for transforming and transpiling JavaScript code. Acorn is lightweight and fast, making it ideal for scenarios where only parsing is needed. Babel, on the other hand, offers more extensive features for code transformation and compatibility with older JavaScript environments, but comes with increased complexity and resource usage.

2,275

Monorepo for the JS language tools.

Pros of js

  • More comprehensive linting and style checking capabilities
  • Extensive plugin ecosystem for customization
  • Integrated into many development workflows and CI/CD pipelines

Cons of js

  • Heavier and slower than Acorn for basic parsing tasks
  • More complex configuration required for optimal use
  • Steeper learning curve for advanced features and customization

Code Comparison

Acorn (basic parsing):

import * as acorn from "acorn";
const ast = acorn.parse("const x = 42;", {ecmaVersion: 2020});

js (linting):

const ESLint = require('eslint').ESLint;
const eslint = new ESLint();
const results = await eslint.lintText("const x = 42;");

Summary

Acorn is a lightweight, fast JavaScript parser, while js is a more comprehensive linting tool. Acorn excels in scenarios requiring quick and efficient parsing, such as in build tools or other JavaScript analysis tasks. js, on the other hand, provides a robust set of rules and plugins for maintaining code quality and consistency across projects. The choice between the two depends on the specific needs of the project, with Acorn being preferable for pure parsing tasks and js being better suited for enforcing coding standards and catching potential errors.

5,093

The ESTree Spec

Pros of estree

  • Provides a standardized AST specification for JavaScript
  • Language-agnostic, allowing implementations in various programming languages
  • Widely adopted by many popular JavaScript tools and libraries

Cons of estree

  • Not an actual parser implementation, only a specification
  • Requires separate implementation efforts for each language or tool
  • May lag behind in supporting the latest JavaScript features

Code comparison

estree (AST specification):

{
  "type": "Program",
  "body": [
    {
      "type": "ExpressionStatement",
      "expression": {
        "type": "Literal",
        "value": 42
      }
    }
  ]
}

Acorn (parser implementation):

const acorn = require('acorn');
const ast = acorn.parse('42');
console.log(JSON.stringify(ast, null, 2));

Key differences

  • estree is a specification, while Acorn is an actual parser implementation
  • Acorn follows the estree specification, producing ASTs that conform to it
  • estree focuses on defining the structure of ASTs, while Acorn handles the parsing process
  • Developers can use Acorn directly in their projects, whereas estree serves as a reference for implementers

Both projects are valuable in the JavaScript ecosystem, with estree providing a common standard and Acorn offering a concrete, high-performance implementation of that standard.

8,615

🗜 JavaScript parser, mangler and compressor toolkit for ES6+

Pros of Terser

  • Focuses on minification and optimization of JavaScript code
  • Offers more advanced compression techniques and options
  • Actively maintained with frequent updates and improvements

Cons of Terser

  • Larger codebase and potentially slower parsing compared to Acorn
  • More complex configuration options may require additional learning

Code Comparison

Acorn (parsing):

import * as acorn from "acorn";
const ast = acorn.parse("const x = 42;", {ecmaVersion: 2020});

Terser (minification):

import { minify } from "terser";
const result = await minify("function add(first, second) { return first + second; }");
console.log(result.code);
// Output: function add(n,d){return n+d}

Summary

Acorn is a lightweight JavaScript parser, while Terser is a JavaScript parser, mangler, and compressor toolkit. Acorn excels in parsing speed and simplicity, making it ideal for tasks requiring AST generation. Terser, on the other hand, specializes in code minification and optimization, offering more advanced features for reducing JavaScript file sizes. The choice between the two depends on the specific requirements of your project, whether you need fast parsing or comprehensive minification capabilities.

30,914

Rust-based platform for the Web

Pros of swc

  • Significantly faster parsing and transpilation due to Rust implementation
  • Broader feature set, including bundling and minification
  • Supports TypeScript and JSX out of the box

Cons of swc

  • Larger project scope, potentially more complex to contribute to
  • Less mature ecosystem and community compared to Acorn
  • May have a steeper learning curve for developers unfamiliar with Rust

Code Comparison

Acorn (JavaScript):

import * as acorn from "acorn";
const ast = acorn.parse("const x = 42;", {ecmaVersion: 2020});

swc (Rust):

use swc_ecma_parser::{lexer::Lexer, Parser, StringInput, Syntax};
let ast = Parser::new(Syntax::Es(Default::default()))
    .parse_module(&source_code)
    .unwrap();

Both projects aim to parse JavaScript, but swc offers a more comprehensive toolset for modern web development, including transpilation and bundling. Acorn, being more focused on parsing, may be easier to integrate into existing JavaScript projects. The choice between them depends on specific project requirements and performance needs.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Acorn

Build Status NPM version CDNJS

A tiny, fast JavaScript parser, written completely in JavaScript.

Community

Acorn is open source software released under an MIT license.

You are welcome to report bugs or create pull requests on github.

Packages

This repository holds three packages:

To build the content of the repository, run npm install.

git clone https://github.com/acornjs/acorn.git
cd acorn
npm install

Plugin developments

Acorn is designed to support plugins which can, within reasonable bounds, redefine the way the parser works. Plugins can add new token types and new tokenizer contexts (if necessary), and extend methods in the parser object. This is not a clean, elegant API—using it requires an understanding of Acorn's internals, and plugins are likely to break whenever those internals are significantly changed. But still, it is possible, in this way, to create parsers for JavaScript dialects without forking all of Acorn. And in principle it is even possible to combine such plugins, so that if you have, for example, a plugin for parsing types and a plugin for parsing JSX-style XML literals, you could load them both and parse code with both JSX tags and types.

A plugin is a function from a parser class to an extended parser class. Plugins can be used by simply applying them to the Parser class (or a version of that already extended by another plugin). But because that gets a little awkward, syntactically, when you are using multiple plugins, the static method Parser.extend can be called with any number of plugin values as arguments to create a Parser class extended by all those plugins. You'll usually want to create such an extended class only once, and then repeatedly call parse on it, to avoid needlessly confusing the JavaScript engine's optimizer.

const {Parser} = require("acorn")

const MyParser = Parser.extend(
  require("acorn-jsx")(),
  require("acorn-bigint")
)
console.log(MyParser.parse("// Some bigint + JSX code"))

Plugins override methods in their new parser class to implement additional functionality. It is recommended for a plugin package to export its plugin function as its default value or, if it takes configuration parameters, to export a constructor function that creates the plugin function.

This is what a trivial plugin, which adds a bit of code to the readToken method, might look like:

module.exports = function noisyReadToken(Parser) {
  return class extends Parser {
    readToken(code) {
      console.log("Reading a token!")
      super.readToken(code)
    }
  }
}

NPM DownloadsLast 30 Days