1. to-ast
Converts JavaScript objects to equivalent ASTs
to-ast
Package: to-ast
Created by: devongovett
Last modified: Mon, 27 Jun 2022 07:22:11 GMT
Version: 1.0.0
License: MIT
Downloads: 508,681
Repository: https://github.com/devongovett/to-ast

Install

npm install to-ast
yarn add to-ast

to-ast

This module converts JavaScript objects to an equivalent abstract syntax tree representation,
compatible with the Mozilla Parser API.
You can use it to generate JavaScript source code from objects, using
escodegen.

Usage

Install with npm:

npm install to-ast

Here's a simple example:

 
var toAST = require('to-ast');
var escodegen = require('escodegen');

// get an AST from a number...
toAST(2) //=> { type: 'Literal', value: 2 }

// or if you want a source string...
escodegen.generate(toAST(2)) //=> '2'

Supported types

  • undefined
  • null
  • number, string, and boolean literals
  • functions
  • Node buffers
  • arrays
  • String, Number, and Boolean object wrappers
  • typed arrays and array buffers
  • dates
  • errors
  • regular expressions
  • object literals

Custom types

Most built-in JavaScript types as supported out of the box, but if you want to override the behavior for
your particular object, you can provide a toAST method on your object:

 var toAST = require('to-ast');
var escodegen = require('escodegen');

function Person(name) {
  this.name = name;
}

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

escodegen.generate(toAST(new Person('Devon'))) //=> "new Person('Devon')"

License

MIT

RELATED POST

10 Must-Know Windows Shortcuts That Will Save You Time

10 Must-Know Windows Shortcuts That Will Save You Time

Arrays vs Linked Lists: Which is Better for Memory Management in Data Structures?

Arrays vs Linked Lists: Which is Better for Memory Management in Data Structures?

Navigating AWS Networking: Essential Hacks for Smooth Operation

Navigating AWS Networking: Essential Hacks for Smooth Operation

Achieving Stunning Visuals with Unity's Global Illumination

Achieving Stunning Visuals with Unity's Global Illumination

Nim's Hidden Gems: Lesser-known Features for Writing Efficient Code

Nim's Hidden Gems: Lesser-known Features for Writing Efficient Code