Get started with acorn CDN

MIT licensed

Acorn parses ECMAScript code into abstract syntax trees .

Tags:
  • acorn
  • javascript
  • parser
  • ECMAScript
  • Escodegen

Stable version

Copied!

How to start using acorn CDN


const Acorn = require('acorn'); // Use require for CommonJS modules in Node.js
const acorn = require('acorn/dist/acorn.min.js'); // Use require for the minified version in the browser
const acornTraverse = require('acorn-traverse'); // For traversing the abstract syntax tree

// Assuming the following expression is in a string variable called `code`
const code = 'const result = 1 + 2 * 3';

// Parse the code using Acorn
const ast = acorn.parse(code, { ecmaVersion: 6 });

// Traverse the abstract syntax tree and transform the expression
acornTraverse(ast, {
  ExpressionStatement(node) {
    if (node.expression.type === 'BinaryExpression') {
      node.expression.right.operand = { type: 'NumericLiteral', value: 4 };
    }
  },
});

// Print the transformed abstract syntax tree
console.log(JSON.stringify(ast, null, 2));

// Compile the transformed abstract syntax tree to JavaScript code
const { code: transformedCode } = Acorn.compile(ast);

// Evaluate the transformed code
const evalResult = new Function('result', transformedCode)('result');
console.log(evalResult); // Output: 1 + 2 * 4 = 7
Copied!
Copied!

All versions