npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

transform-ast

v2.4.4

Published

transform an AST with source maps

Downloads

392,306

Readme

transform-ast

Transform an AST with source maps. Basically @substack's falafel, but based on magic-string.

Example

var result = require('transform-ast')(`
  var multiply = (a, b) => {
    return a * b
  }
  var add = (a, b) => a + b
`, function (node) {
  if (node.type === 'ArrowFunctionExpression') {
    var params = node.params.map(function (param) { return param.getSource() })
    if (node.body.type !== 'BlockStatement') {
      node.body.edit.update(`{ return ${node.body.getSource()} }`)
    }
    node.edit.update(`function (${params.join(', ')}) ${node.body.getSource()}`)
  }
})
result.toString() === `
  var multiply = function (a, b) {
    return a * b
  }
  var add = function (a, b) { return a + b }
`
fs.writeFile('output.js.map', JSON.stringify(result.map))

Install

npm install --save transform-ast

API

magicString = transformAst(source, opts = {}, fn = function () {})

Parse and transform a source string. fn will be called on each node. The returned magicString is a magic-string instance, with a toString() method to get the transformed string and a .map property to access the source map.

opts.parser sets the parser module to use. This should be an object with a .parse(src, opts) function. The default is require('acorn-node').

If you already have an AST, pass it in opts.ast. This will skip the parse step inside transformAst().

transformAst(source, { ast: parsedSource }, cb)

magicString.walk(fn)

Walk the AST again. fn will be called on each node.

magicString.map

Generate and return a source map. If the input source had an inline source map comment, this will be taken into account, and the final source map will point back to the original string. The source map for only the changes made by transform-ast can be accessed by using magic-string's generateMap() method.

nodes

In addition to the usual AST node properties, each node object also has some additional methods. Unlike falafel, these methods live on the .edit property, to prevent name conflicts (such as the update() method and the .update property of a ForStatement). They're still also defined on the nodes themselves, but only if there is no naming conflict. It's better to use the .edit property.

node.getSource(), node.edit.source()

Get the source string for a node, including transformations.

node.edit.update(string)

Replace node with the given string.

node.edit.append(string)

Append the source string after this node.

node.edit.prepend(string)

Prepend the source string before this node.

Custom Parser

You can pass in a custom parser using the parser option. The parser should be an object with a parse function that takes a string and returns an AST. Each AST node should have .start and .end properties indicating their position in the source string.

For example, parsing JSX using babylon:

var babylon = require('babylon')
var transform = require('transform-ast')
var assert = require('assert')

assert.equal(transform(`
  var el = <div />;
`, { parser: babylon, plugins: [ 'jsx' ] }, function (node) {
  if (node.type === 'JSXElement') {
    node.edit.update(JSON.stringify(node.source()))
  }
}).toString(), `
  var el = "<div />";
`)

But parsers for other languages too, like tacoscript's parser module horchata:

var horchata = require('horchata')
var transform = require('transform-ast')
var assert = require('assert')

assert.equal(transform(`
X = () -> {
  @prop or= 'value'
}
new X
`, { parser: horchata }, function (node) {
  switch (node.type) {
  case 'FunctionExpression':
    node.edit.update('function () ' + node.body.getSource())
  }
}).toString(), `
X = function () {
  @prop or= 'value'
}
new X
`)

License

MIT