How to Use ES6 for
Universal JavaScript Apps

Eric Elliott
Apr 28, 2015 · 4 min read

Use Babel

Babel.js is a great tool that lets you transpile your ES6 code into ES5 code that runs in today’s JavaScript environments, including Node.js and browsers, but it isn’t obvious how to get it set up.


Install Babel

Nearly every tutorial you find will tell you to install Babel globally. That’s fine if nobody has to share your code, but if you’re on a team or producing open-source libraries, install it locally per-package, as well:

$ npm install -g babel-cli
$ npm install --save-dev babel-cli babel-preset-es2015 babel-preset-stage-0
$ babel-node
> Object.assign({}, {msg: 'wow!'}); // => { msg: 'wow!' }
$ npm install --save-dev babelify browserify
(x) => x + 1;
Object.is(NaN, NaN); // => true
$ npm install --save core-js
import 'core-js';

Linting

Worried that you’ll have to give up linting your code? No worries. ESLint has you covered!

$ npm install --save-dev eslint babel-eslint


Compiling

For most cases, you can simply replace your `node` calls with `babel-node` calls. `babel-node` caches modules in memory, so there’s a significant startup delay and potentially a lot of memory usage. Consider compiling to to ES5 for production. Read on.

$ babel script.js --out-file script-compiled.js
$ babel -d build-dir source-dir
$ babel -d build-dir source-dir -s
npm install -g browserify browser-run
browserify -t babelify script.js | browser-run -p 2222
  1. Create a bundle from `script.js` and run the script in chrome. Hit http://localhost:2222 from your favorite browser, and the script will run in the browser. Console log output will get piped back to the console.
$ browserify script.js -t babelify --outfile bundle.js

Using Existing Modules

Using the above mentioned tools, you can import both ES6 and Node-style modules using ES6 syntax:

import 'core-js'; // Node module
import harness from './harness'; // ES6 module

Automation

I like to put these commands in my npm scripts:

React

Bonus for React users: you’re covered, too. Both Babel and ESLint support JSX. Nice!

npm install --save-dev babel@5.8.29

Party Time

Congratulations! You’re ready to start using ES6 for your universal apps. In case you’re wondering, here are a few of my favorite ES6 things you should explore:

  • Destructuring
  • Arrow functions (Great for one-line lambdas)
  • Default params
  • Rest params
  • Generators

Enjoy!



JavaScript Scene

JavaScript, software leadership, software development, and related technologies.

Eric Elliott

Written by

Make some magic. #JavaScript

JavaScript Scene

JavaScript, software leadership, software development, and related technologies.