Using Babel

How to use Babel with your tool of choice

1 Choose your tool

Babel built-ins
Build systems
Frameworks
Test frameworks
Utilities
Language APIs
Template engines
Editors and IDEs
Debuggers

2 Installation

CLI

While you can install Babel CLI globally on your machine, it’s much better to install it locally project by project.

There are two primary reasons for this.

  1. Different projects on the same machine can depend on different versions of Babel allowing you to update one at a time.
  2. It means you do not have an implicit dependency on the environment you are working in. Making your project far more portable and easier to setup.

We can install Babel CLI locally by running:

$ npm install --save-dev babel-cli

Note: Since it's generally a bad idea to run Babel globally you may want to uninstall the global copy by running npm uninstall --global babel-cli.

After that finishes installing, your package.json file should look like this:

{
  "name": "my-project",
  "version": "1.0.0",
  "devDependencies": {
    "babel-cli": "^6.0.0"
  }
}

Require hook

$ npm install babel-register

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.

MSBuild

Support for Babel in .NET is provided by the ReactJS.NET project. Install the MSBuild task via NuGet:

Install-Package React.MSBuild

RequireJS

$ npm install requirejs-babel

Rollup

$ npm install --save-dev rollup
$ npm install --save-dev rollup-plugin-babel
# Instead of the es2015 preset
$ npm install --save-dev babel-preset-es2015-rollup

Sprockets

$ gem install sprockets-es6

Webpack

$ npm install --save-dev babel-loader babel-core

Fly

$ npm install -D fly-babel babel-preset-es2015

Start

$ npm install -D start-babel

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

AVA

There is no need to install babel-core, AVA bundles it already.

Jasmine

$ npm install --save-dev babel-register

Jest

$ npm install --save-dev babel-jest

Karma

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

Lab

$ npm install --save-dev lab-babel

Mocha

$ npm install --save-dev babel-register

Connect

$ npm install babel-connect

Nodemon

$ npm install babel-cli babel-preset-es2015 --save-dev

C# / .NET

Support for Babel in .NET is provided by the ReactJS.NET project. The core library can be installed via NuGet:

Install-Package React.Core

Node

$ npm install --save-dev babel-core

Ruby

$ gem install babel-transpiler

Jade

$ npm install jade-babel

WebStorm

$ npm install --save-dev babel-cli

Node Inspector

$ npm install -g babel-node-debug

3 Usage

CLI

Instead of running Babel directly from the command line we’re going to put our commands in npm scripts which will use our local version.

Simply add a "scripts" field to your package.json and put the babel command inside there as build.

  {
    "name": "my-project",
    "version": "1.0.0",
+   "scripts": {
+     "build": "babel src -d lib"
+   },
    "devDependencies": {
      "babel-cli": "^6.0.0"
    }
  }

Now from our terminal we can run:

$ npm run build

This will run Babel the same way as before and the output will be present in lib directory, only now we are using a local copy.

Alternatively, you can reference the babel cli inside of node_modules.

$ ./node_modules/.bin/babel src -d lib

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

Require hook

To include it you will need to require it at the top of the entry point to your application.

require("babel-register");

If you are using ES6’s import syntax in your application’s entry point, you should instead import at the top of the entry point to ensure it is loaded first:

import "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.

Not meant for production use

The require hook is primarily recommended for simple cases.

For full documentation on the Babel require hook 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 --comments false ]
Node API
browserify().transform(babelify.configure({
  comments: false
}))
package.json
{
  "transform": [["babelify", { "comments": false }]]
}

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 .babelrc
  mkdir -p $(@D)
  babel $< -o $@
$ make

MSBuild

Import the task in your MSBuild script:

<UsingTask AssemblyFile="packages\React.MSBuild.2.1.0\React.MSBuild.dll" TaskName="TransformBabel" />

Use it:

<TransformBabel SourceDir="$(MSBuildProjectDirectory)" TargetDir="" />

This will transform every .js and .jsx file in the directory, and output a .generated.js file alongside it.

See http://reactjs.net/guides/msbuild.html for more information

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.

Fly

  export function* text () {
    yield this
      .source("src/**/*.js")
      .babel({ presets: ["es2015"] })
      .target("dist/")
  }

For more information see the bucaran/fly-babel repo.

Start

import Start from 'start';
import reporter from 'start-pretty-reporter';
import files from 'start-files';
import read from 'start-read';
import babel from 'start-babel';
import write from 'start-write';

const start = Start(reporter());

export function build() {
  return start(
    files('lib/**/*.js'),
    read(),
    babel({ sourceMaps: true }),
    write('build/')
  );
}

For more information see the start-runner/babel 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.

AVA

AVA ships with ES2015 support built-in using Babel 6 under the hood, so you can write test using ES2015 syntax right away.

The AVA default Babel configuration includes the "es2015" and "stage-2" presets, but you can customize any Babel option for transpiling test files with the "babel" option in AVA’s package.json configuration.

For example:

{
  "ava": {
    "babel": {
      "presets": [
        "es2015",
        "react"
      ]
    }
  }
}

Or you can simply "inherit" the Babel configuration from .babelrc or Babel’s package.json configuration, making test files use the same configuration as your source files:

{
  "ava": {
    "babel": "inherit"
  }
}

Note that AVA always adds a few custom Babel plugins when transpiling your plugins see notes.

For more information see the AVA recipe on how to configure Babel.

Jasmine

In your spec/support/jasmine.json file make the following changes:

{
  "helpers": [
    "../node_modules/babel-register/lib/node.js"
  ]
}

This file is created when you setup a project with the jasmine init command.

For more information see the piecioshka/test-jasmine-babel repo.

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.

Lab

When running tests with lab set the transpiler to lab-babel:

lab -T node_modules/lab-babel

Mocha

In your package.json file make the following changes:

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

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 --presets=es2015 --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 --presets=es2015 --ignore='foo\|bar\|baz' -- path/to/script.js

C# / .NET

var babel = ReactEnvironment.Current.Babel;
// Transpiles a file
// You can instead use `TransformFileWithSourceMap` if you want a source map too.
var result = babel.TransformFile("foo.js");
// Transpiles a piece of code
var result = babel.Transform("class Foo { }");

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 a .js extension 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.

Note

Pre-6.x, Babel enabled certain transformations by default. However, Babel 6.x does not ship with any transformations enabled. You need to explicitly tell it what transformations to run. The simplest way to do this is by using a preset, such as the ES2015 Preset. You can install it with

npm install babel-preset-es2015 --save-dev
(In order to emulate a full ES2015+ environment, you will need to use a polyfill (one option is babel-polyfill) for things like Promise, Set, Map, or instance methods like String.repeat or Array.includes since Babel only does syntax transformations.

Warning!

Babel 6 was just released! This means that it might take some time for all possible integrations to upgrade. Make sure to check the compatibility of your chosen integration.

4 Create .babelrc configuration file

Great! You've configured Babel but you haven't made it actually do anything. Create a .babelrc config in your project root and enable some plugins.

Assuming you have installed the ES2015 Preset, in order to enable it you have to define it in your .babelrc file, like this:

{
  "presets": ["es2015"]
}
      

Note: Running a Babel 6.x project using npm 2.x can cause performance problems because of the way npm 2.x installs dependencies. This problem can be eliminated by either switching to npm 3.x or running npm 2.x with the dedupe flag. To check what version of npm you have run

npm --version