JSPM

morpher

0.2.1
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 3
  • Score
    100M100P100Q37851F
  • License MIT

JavaScript AST transformer and code generator

Package Exports

  • morpher

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 (morpher) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Morpher

Build Status

JavaScript AST transformer and code generator, optimized for older engines.

Inspired by falafel (https://github.com/substack/node-falafel) and free-falafel (https://github.com/freethenation/node-falafel), but modified for performance in older JavaScript engines (eg. IE8.)

AST traversal is leaf-first (so child nodes are visited before their parents.)

Example

var code = 'var result = 1 + 2;';
var ast = acorn.parse(code, {ranges: true});
var transpiledCode = morpher.morph(code, ast, function (node, parent, replace, source) {
    if (node.type === 'BinaryExpression') {
        replace(node, 'postProcess(' + source(node) + ')');
    }
});
console.log(transpiledCode); // Outputs `var result = postProcess(1 + 2);`

Use with a breadth-first callback

To process parent nodes before their children, you can pass a second callback to .morph(...):

var code = 'var result = 1 + 2; function test() { return 2 + 3; }';
var ast = acorn.parse(code, {ranges: true});
var transpiledCode = morpher.morph(code, ast, function (node, parent, replace, source) {
    if (node.type === 'BinaryExpression' && node.inFunc) {
        replace(node, 'postProcess(' + source(node) + ')');
    }
}, function (node, parent) {
    if (parent) {
        node.inFunc = parent.inFunc;
    }

    if (node.type === 'FunctionDeclaration') {
        node.inFunc = true;
    }
});
console.log(transpiledCode); // Outputs `var result = 1 + 2; function test() { return postProcess(2 + 3); }`

Keeping up to date