JavaScript Object to AST Converter

1.0.0 · maintenance · verified Sun Apr 19

The `to-ast` package, currently at version 1.0.0, provides a utility for converting standard JavaScript objects and primitive values into a Mozilla Parser API-compatible Abstract Syntax Tree (AST) representation. This library is specifically designed to facilitate the generation of JavaScript source code from data structures, often used in conjunction with tools like `escodegen`. It supports a wide range of built-in types including primitives (numbers, strings, booleans, undefined, null), functions, arrays, buffers, dates, errors, regular expressions, and object literals. A key differentiator is its ability to handle custom types by respecting a `toAST` method on the object's prototype, allowing for custom AST representations. Given its singular purpose and stable version, its release cadence is likely low, operating more as a specialized, maintenance-mode utility.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates converting primitive and custom JavaScript objects into ASTs, and then generating source code using escodegen.

const toAST = require('to-ast');
const escodegen = require('escodegen'); // Often used in conjunction with to-ast

// Convert a number literal to its AST representation
const numberAst = toAST(2);
console.log('AST for 2:', JSON.stringify(numberAst, null, 2));
// Expected output: {"type":"Literal","value":2}

// Generate source code from the AST
const numberSource = escodegen.generate(numberAst);
console.log('Source for 2:', numberSource);
// Expected output: 2

// Demonstrate custom type conversion using a 'toAST' method
function Person(name) {
  this.name = name;
}

Person.prototype.toAST = function() {
  return {
    type: 'NewExpression',
    callee: { type: 'Identifier', name: 'Person' },
    arguments: [{ type: 'Literal', value: this.name }]
  };
};

const personInstance = new Person('Devon');
const personAst = toAST(personInstance);
console.log('AST for Person:', JSON.stringify(personAst, null, 2));
/* Expected output:
{
  "type": "NewExpression",
  "callee": {
    "type": "Identifier",
    "name": "Person"
  },
  "arguments": [
    {
      "type": "Literal",
      "value": "Devon"
    }
  ]
}
*/

const personSource = escodegen.generate(personAst);
console.log('Source for Person:', personSource);
// Expected output: new Person('Devon')

view raw JSON →