Babel

June 23, 2016

There are new versions of Javascript (ES6, ES7) full of new features and a ton of syntax shortcuts. For example:

() =>
  2

…is shorthand for an anonymous function that returns 2.

As with everything in programming, people can’t agree on anything and browsers are slow to implement stuff. We’d have jetpacks before browsers implemented it correctly/consistently so some cool people made some things called “transpilers” that convert ES6+ to usable old-fashioned Javascript (ES5). The most popular one is Babel.

Here’s what it converts the above code to.

Babel works with just about any build process, and is extendable with modular plugins.

How to use it

The easiest/cleanest way is installing some npm packages and configuring it in package.json. We’ll make an npm script for it so we can run something like npm run dev from the terminal.

"babel": {
  "presets": [
    "es2015",
    "stage-0"
  ]
}

Protip: You transpile CSS (Sass, Stylus, LESS, PostCSS, etc.) and HTML (Pug/Jade, Haml, etc.) as well. Currently most companies organize this stuff as src/css, src/js, src/html, etc. but I think component architecture is a better solution for larger projects so try it out if you can.

package.json should look like this (if you copy this make sure you run npm i before using it):

{
  "devDependencies": {
    "babel-cli": "^6.10.1",
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-stage-0": "^6.5.0"
  },
  "babel": {
    "presets": [
      "es2015",
      "stage-0"
    ]
  },
  "scripts": {
    "dev": "babel -w src -d dist"
  }
}

Congrats

Now you’re able to use ES6/7. Not only that, but you’re using package.json scripts to perform tasks which is pretty nice as long as a CLI for a particular tool is available (if one isn’t, consider doing everyone a favor and making one).

Homework