JSPM

  • Created
  • Published
  • Downloads 3151529
  • Score
    100M100P100Q211130F
  • License MIT

JavaScript code generator from an ESTree-formatted AST node.

Package Exports

  • astring

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (astring) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Astring

Build Status NPM Version

A tiny and fast JavaScript code generator from an ESTree-formatted AST.

Key features:

  • Supports ECMAScript versions 5 and 6.
  • Considerably faster than Escodegen.
  • Smaller than Esotope and faster for small ASTs.
  • No dependencies and small footprint (12 KB minified, 3 KB gziped).
  • Output code is readable and executable.
  • Reduced formatting options.

Installation

If you haven't already, install the Node Package Manager.

The easiest way is to install it with the Node Package Manager:

npm install astring

Alternatively, checkout this repository and install the development dependencies:

git clone https://github.com/davidbonnet/astring.git
cd astring
npm install

Usage

The path to the module file is dist/astring.min.js and works both in a browser or Node environment. When run in a browser, it creates a global variable astring.

The astring module consists of a function that takes two arguments: node and options. It returns a string representing the rendered code of the provided AST node. The options are:

  • indent: string to use for indentation (defaults to \t)
  • lineEnd: string to use for line endings (defaults to \n)
  • startingIndentLevel: indent level to start from (defaults to 0)

Example

This example uses Acorn, a blazingly fast JavaScript parser and AST producer. It is the perfect companion of Astring.

// Import modules (unecessary when run in a browser)
acorn = require( 'acorn' );
astring = require( 'astring' );

// Example code
var code = "let answer = 4 + 7 * 5 + 3;\n";

// Parse it into an AST
var ast = acorn.parse( code, { ecmaVersion: 6 } );

// Set formatting options
var options = {
    indent: '   ',
    lineEnd: '\n'
};

// Format it
var result = astring( ast, options );

// Check it
if ( code === result ) {
    console.log( 'It works !' );
} else {
    console.log( 'Something went wrong…' );
}

TODO

  • CLI
  • Comments generation
  • More tests