Using Babel

How to use Babel with your tool of choice

1 Choose your tool

Babel built-ins
CLI
Require hook
Browser
Build systems
Broccoli
Browserify
Brunch
Duo
Gobble
Grunt
Gulp
jspm
Make
RequireJS
Rollup
Sprockets
Webpack
Frameworks
Ember
Meteor
Rails
Sails
Test frameworks
Mocha
Jest
Karma
Utilities
Connect
Nodemon
Language APIs
Node
Ruby
Template engines
Jade
Editors and IDEs
WebStorm
Debuggers
Node Inspector

2 Install

CLI

$ npm install -g babel

Require hook

$ npm install -g babel

Browser

Available from browser.js inside the folder of a babel-core npm release.

Broccoli

$ npm install --save-dev broccoli-babel-transpiler

Browserify

$ npm install --save-dev babelify

Brunch

$ npm install --save-dev babel-brunch

Duo

$ npm install --save-dev duo-babel

Gobble

$ npm install --save-dev gobble-babel

Grunt

$ npm install --save-dev grunt-babel

Gulp

$ npm install --save-dev gulp-babel

jspm

Select babel as the transpiler when running jspm init -p or to switch an existing project into Babel use:

  jspm dl-loader --babel

Make

Installed already on most Unix systems. Available from gow on Windows.

RequireJS

$ npm install requirejs-babel

Rollup

$ npm install --save-dev rollup
$ npm install --save-dev rollup-plugin-babel

Sprockets

$ gem install sprockets-es6

Webpack

$ npm install --save-dev babel-loader

Ember

npm install --save-dev ember-cli-babel

Meteor

$ meteor add ecmascript

Rails

$ gem install sprockets-es6

Sails

$ npm install --save-dev sails-hook-babel

Mocha

$ npm install --save-dev babel

Jest

$ npm install --save-dev babel-jest

Karma

$ npm install --save-dev karma-babel-preprocessor

Connect

$ npm install babel-connect

Nodemon

$ npm install -g babel

Node

$ npm install --save-dev babel-core

Ruby

$ gem install babel-transpiler

Jade

$ npm install jade-babel

WebStorm

$ npm install -g babel

Node Inspector

$ npm install -g babel-node-debug

3 Usage

CLI

$ babel script.js

For full documentation on the Babel CLI see the usage docs.

Require hook

require("babel/register");

All subsequent files required by node with the extensions .es6, .es, .jsx and .js will be transformed by Babel. The polyfill specified in polyfill is also automatically required.

Not suitable for libraries

The require hook automatically hooks itself into all node requires. This will pollute the global scope and introduce conflicts. Because of this it's not suitable for libraries, if however you're writing an application then it's completely fine to use.

For full documentation on the Babel require hook see the usage docs.

Browser

Add the type="text/babel" attribute to your <script> tags. For example:

<script src="node_modules/babel-core/browser.js"></script>
<script type="text/babel">
class Test {
  test() {
    return "test";
  }
}

var test = new Test;
test.test(); // "test"
</script>

For full documentation on browser compilation see the usage docs.

Broccoli

var babelTranspiler = require("broccoli-babel-transpiler");
var scriptTree = babelTranspiler(inputTree, options);

For more information see the babel/broccoli-babel-transpiler repo.

Browserify

Via CLI

$ browserify script.js -t babelify --outfile bundle.js

Via Node API

browserify({ debug: true })
  .transform(babelify);

Or a more complete example:

var fs = require("fs");
var browserify = require("browserify");
var babelify = require("babelify");

browserify({ debug: true })
  .transform(babelify)
  .require("./script.js", { entry: true })
  .bundle()
  .on("error", function (err) { console.log("Error: " + err.message); })
  .pipe(fs.createWriteStream("bundle.js"));

Passing options

CLI

$ browserify -d -e script.js -t [ babelify --blacklist regenerator ]
Node API
browserify().transform(babelify.configure({
  blacklist: ["regenerator"]
}))
package.json
{
  "transform": [["babelify", { "blacklist": ["regenerator"] }]]
}

For more information see the babel/babelify repo.

Brunch

That's it! Set babel options in your brunch config (such as brunch-config.coffee) except for filename and sourceMap which are handled internally.

plugins:
  babel:
    whitelist: ["arrowFunctions"]
    format:
      semicolons: false

For more information see the babel/babel-brunch repo.

Duo

Via CLI

$ duo --use duo-babel

Via Node API

Duo(root)
  .entry(entry)
  .use(babel)
  .run(fn);

For more information see the babel/duo-babel repo.

Gobble

var gobble = require("gobble");
module.exports = gobble("src").transform("babel", options);

For more information see the babel/gobble-babel repo.

Grunt

require("load-grunt-tasks")(grunt); // npm install --save-dev load-grunt-tasks

grunt.initConfig({
  "babel": {
    options: {
      sourceMap: true
    },
    dist: {
      files: {
        "dist/app.js": "src/app.js"
      }
    }
  }
});

grunt.registerTask("default", ["babel"]);

For more information see the babel/grunt-babel repo.

Gulp

var gulp = require("gulp");
var babel = require("gulp-babel");

gulp.task("default", function () {
  return gulp.src("src/app.js")
    .pipe(babel())
    .pipe(gulp.dest("dist"));
});

With source maps

Use gulp-sourcemaps like this:

var gulp = require("gulp");
var sourcemaps = require("gulp-sourcemaps");
var babel = require("gulp-babel");
var concat = require("gulp-concat");

gulp.task("default", function () {
  return gulp.src("src/**/*.js")
    .pipe(sourcemaps.init())
    .pipe(babel())
    .pipe(concat("all.js"))
    .pipe(sourcemaps.write("."))
    .pipe(gulp.dest("dist"));
});

For more information see the babel/gulp-babel repo.

jspm

Babel will automatically be used when loading any source with import or export module syntax.

JSX support is currently disabled by jspm. To re-enable it, add `"blacklist": []` to `babelOptions` in the jspm configuration file.

Make

SRC = $(wildcard src/*.js)
LIB = $(SRC:src/%.js=lib/%.js)

lib: $(LIB)
lib/%.js: src/%.js
  mkdir -p $(@D)
  babel $< -o $@
$ make

RequireJS

Add the following paths to your configuration:

paths: {
  es6: "node_modules/requirejs-babel/es6",
  babel: "node_modules/requirejs-babel/babel-4.6.6.min"
}

Then reference files via the es6! plugin name:

define(["es6!your-es6-module"], function (module) {
  // ...
});

For more information see the mikach/requirejs-babel repo.

Rollup

var rollup = require("rollup");
var babel = require("rollup-plugin-babel");

rollup.rollup({
  entry: "src/main.js",
  plugins: [ babel() ]
}).then(function (bundle) {
  bundle.write({
    dest: "dist/bundle.js",
    format: "umd"
  });
});

For more information see the rollup and rollup-plugin-babel repos.

Sprockets

# Gemfile
gem "sprockets"
gem "sprockets-es6"
require "sprockets/es6"

For more information see the TannerRogalsky/sprockets-es6 repo.

Webpack

Via config

module: {
  loaders: [
    { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"}
  ]
}

Via loader

var Person = require("babel!./Person.js").default;
new Person();

For more information see the babel/babel-loader repo.

Ember

That's it!

For more information see the babel/ember-cli-babel repo.

Meteor

That's it! Any files with a .js extension will automatically be compiled with Babel.

As of Meteor 1.2, the ecmascript package is installed by default for all new apps, so meteor add ecmascript is only necessary for existing apps.

For more information see the ecmascript README.md.

Rails

# Gemfile
gem "sprockets"
gem "sprockets-es6"
require "sprockets/es6"

For more information see the TannerRogalsky/sprockets-es6 repo.

Sails

That's it!

For more information see the artificialio/sails-hook-babel repo.

Mocha

In your package.json file make the following changes:

{
  "scripts": {
    "test": "mocha --compilers js:babel/register"
  }
}

Jest

In your package.json file make the following changes:

{
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
    "testFileExtensions": ["es6", "js"],
    "moduleFileExtensions": ["js", "json", "es6"]
  }
}

For more information see the babel/babel-jest repo.

Karma

module.exports = function(config) {
  config.set({
    files: [
      "src/**/*.js",
      "test/**/*.js"
    ],
    preprocessors: {
      "src/**/*.js": ["babel"],
      "test/**/*.js": ["babel"]
    },
    "babelPreprocessor": {
      // options go here
    }
  });
};

For more information see the babel/karma-babel-preprocessor repo.

Connect

var babelMiddleware = require("babel-connect");

app.use(babelMiddleware({
  options: {
    // options to use when transforming files
  },
  src: "assets",
  dest: "cache"
}));

app.use(connect.static("cache"));

For more information see the babel/babel-connect repo.

Nodemon

In your package.json file make the following changes:

{
  "scripts": {
    "babel-node": "babel-node --stage 0 --ignore='foo|bar|baz'"
  }
}

Then call your script with:

$ nodemon --exec npm run babel-node -- path/to/script.js

Arguments caveat

Calling nodemon with babel-node may lead to arguments getting parsed incorrectly if you forget to use a double dash. Using npm-scripts helpers prevent this. If you chose to skip using npm-scripts, it can be expressed as:

$ nodemon --exec babel-node --stage 0 --ignore='foo\|bar\|baz' -- path/to/script.js

Node

require("babel-core").transform("code", options);

For full documentation on the Babel API see the usage docs.

Ruby

require 'babel/transpiler'
Babel::Transpiler.transform File.read("foo.es6")

For more information see the babel/ruby-babel-transpiler repo.

Jade

var jade = require("jade");
var babel = require("jade-babel");

jade.filters.babel = babel({});

OR

var jade = require("jade");
var babel = require("jade-babel");

jade = babel({}, jade);

Now you can use ES6 in your jade templates as following.

script
  :babel
    console.log("Hello World !!!");
    class Person {
      constructor(name) {
        this.name = name;
      }
      sayName(){
        console.log(`Hello, my name is ${this.name}`);
      }
    }
    var person = new Person("Apoxx");
    person.sayName();

For more information see the babel/jade-babel repo.

WebStorm

In Preferences | Tools | File watchers, click + button and select Babel file watcher from the list.

Specify the path to Babel executable and click Ok.

By default all files with .js and .jsx extensions will be automatically compiled with Babel upon change. The generated ES5 files and source maps will be saved next to original files.

Lastly, in Languages & Frameworks | JavaScript | JavaScript language version, choose ECMAScript 6.

For more information see the post in the WebStorm blog.

Node Inspector

$ babel-node-debug path/to/script.js

# Or use the alias

$ bode-debug path/to/script.js

For more information see the crabdude/babel-node-debug repo.