Using Babel

Guides on how to setup babel in whatever environment you might be working in.

Find your guide

It doesn't matter if you're using Node.js or Rails, Gulp or Grunt, there's likely a guide on this page to help guide you. Go ahead and ⌘ + F whatever you're looking for. If it doesn't happen to be on this page you might want to stop by our support chat.

Node.js

CLI

Install

$ npm install --global babel

Usage

$ babel script.js

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

Require Hook

Install

$ npm install babel

Usage

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

require("babel/register");

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.

Rails

Sprockets

See sprockets-es6's repo for more info. If you find any bugs please report them.

Issues with the output should be reported on the babel issue tracker.

Install

$ gem install sprockets-es6

Usage

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

Build Systems

Broccoli

See broccoli-babel-transpiler's repo for more info. If you find any bugs please report them.

Issues with the output should be reported on the babel issue tracker.

Install

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

Usage

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

Source maps

Currently this plugin only support inline source maps. If you need separate source map feature, we welcome you to submit a pull request.

Browserify

See babelify's repo for more info. If you find any bugs please report them.

Issues with the output should be reported on the babel issue tracker.

Install

$ npm install --save-dev babelify

Usage via CLI

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

Usage via Node.js

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

$ browserify -d -e script.js -t [ babelify --blacklist generators ]
browserify().transform(babelify.configure({
  blacklist: ["generators"]
}))

More info

For more information see the babelify README

Brunch

See babel-brunch's repo for more info. If you find any bugs please report them.

Issues with the output should be reported on the babel issue tracker.

Install

$ npm install --save-dev babel-brunch

Configuring

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

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

Duo

See duo-babel's repo for more info. If you find any bugs please report them.

Issues with the output should be reported on the babel issue tracker.

Install

$ npm install --save-dev duo-babel

Usage via CLI

$ duo --use duo-babel

Usage via Node.js

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

Gobble

See gobble-babel's repo for more info. If you find any bugs please report them.

Issues with the output should be reported on the babel issue tracker.

Install

$ npm install --save-dev gobble-babel

Usage

The options argument, if specified, is passed to babel.

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

Source maps

Sourcemaps are created by default (all the relevant information is filled in by Gobble, you don't need to specify sourceMapName options etc). If you don't want that, pass sourceMap: false.

Grunt

See grunt-babel's repo for more info. If you find any bugs please report them.

Issues with the output should be reported on the babel issue tracker.

Install

$ npm install --save-dev grunt-babel

Usage

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"]);

Gulp

See gulp-babel's repo for more info. If you find any bugs please report them.

Issues with the output should be reported on the babel issue tracker.

Install

$ npm install --save-dev gulp-babel

Usage

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"));
});

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(concat("all.js"))
    .pipe(babel())
    .pipe(sourcemaps.write("."))
    .pipe(gulp.dest("dist"));
});

Make

Install

$ npm install --global babel

Usage

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

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

Webpack

See babel-loader's repo for more info. If you find any bugs please report them.

Issues with the output should be reported on the babel issue tracker.

Install

$ npm install --save-dev babel-loader

Usage via loader

import Animal from "babel!./Animal.js";

class Person extends Animal {
  constructor(arg="default") {
    this.eat = "Happy Meal";
  }
}

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

Usage via config

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

and then import normally:

import Person from "./Person.js";

Troubleshooting

For additional information on how to troubleshoot babel-loader please see the README.

Misc

Connect

See babel-connect's repo for more info. If you find any bugs please report them.

Issues with the output should be reported on the babel issue tracker.

Install

$ npm install babel-connect

Usage

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

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

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

Jade

See jade-babel's repo for more info. If you find any bugs please report them.

Issues with the output should be reported on the babel issue tracker.

Install

$ npm install jade-babel

Usage

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();

Jest

See babel-jest's repo for more info. If you find any bugs please report them.

Issues with the output should be reported on the babel issue tracker.

Install

$ npm install --save-dev babel-jest

Usage

In your package.json file please make the following changes:

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

Karma

See karma-babel-preprocessor's repo for more info. If you find any bugs please report them.

Issues with the output should be reported on the babel issue tracker.

Install

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

Usage

See babel options for more details.

Given options properties are passed to babel with no change except:

  • filename
  • sourceMapName
  • sourceFileName

Because they should differ from file to file, corresponding configuration functions are available.

For example, inline sourcemap configuration would look like the following.

module.exports = function(config) {
  config.set({
    files: [
      "src/**/*.js",
      "test/**/*.js"
    ],
    preprocessors: {
      "src/**/*.js": ["babel"],
      "test/**/*.js": ["babel"]
    },
    "babelPreprocessor": {
      options: {
        sourceMap: "inline"
      },
      filename: function(file) {
        return file.originalPath.replace(/\.js$/, ".es5.js");
      },
      sourceFileName: function(file) {
        return file.originalPath;
      }
    }
  });
};

Mocha

Install

$ npm install --save-dev babel

Usage

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

Nodemon

Install

$ npm install --global babel

Usage

In your package.json add a script:

{
  "scripts": {
    "babel-node": "babel-node --experimental --cache --ignore='foo|bar|baz'"
  }
}
$ nodemon --exec npm run babel-node -- path/to/script.js

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