Plugins

How to use and write plugins for Babel

Highly experimental

Internal APIs are still in a high state of flux. If you find something that is not documented on this page then you're at risk of it changing without notice.

Incomplete

Pull requests expanding on existing or adding additional documentation are extremely appreciated.

Official and Community Plugins

Checkout official plugins in the babel-plugins repo! Other community plugins can be found on npm.

Usage

Plugins are resolved relative to the current working directory.

Node API:

require("babel").transform("code", {
  plugins: ["foo-bar"]
});
require("babel").transform("code", {
  plugins: [require("foo-bar")]
});

CLI:

$ babel --plugins foo-bar script.js

babelrc:

{
  "plugins": ["foo-bar"]
}

Specifying position

By default, plugins are run before the internal ones. You can alternatively specify the position via a colon after the plugin name. ie:

require("babel").transform("code", {
  plugins: ["foo-bar:after", "bar-foo:before"]
});
require("babel").transform("code", {
  plugins: [{transformer: require("foo-bar"), position: 'after'}]
});
$ babel --plugins foo-bar:after bar-foo:before script.js

AST documentation

The Babel parser is heavily based on Acorn which makes use of the extremely common and versatile ESTree AST format:

Plugin setup

package.json

{
  "name": "babel-plugin-foo",
  "version": "1.0.0",
  "dependencies": {
    "babel-core": "^5.6.0"
  }
}

index.js

export default function ({ Plugin, types: t }) {
  return new Plugin("foo-bar", {
    visitor: {
      // visitors
    }
  });
}

You can find a simple plugin example as well as usage in the sebmck/babel-plugin-example repo.

Plugin API

Visiting

How to visit nodes

Manipulation

How to remove and replace nodes

Scope

How to use scoping and track variables