Introduction to Babel

Published Oct 11, 2017Last updated Apr 09, 2018
Introduction to Babel

This article is part of a series. You may start from where we left off or clone the git repo and checkout this branch like so.

git clone  
cd webpack-course  
git checkout babel1  

Life is getting pretty happy for our Developer Experience. So far we’ve only used part of the real power of javascript. We’ve been limited by what what features of javascript our current browser can run. When you’re developing in Chrome Canary, everything looks peachy, but ship this same stuff to internet explorer or android and we start seeing syntax errors. Old browsers don’t know it, but we still want to use it. Enter the transpilers to turn shiney new syntax into totally usable old syntax.

Babel is an integral part of Webpack's power. It was created by Facebook and, much like Webpack, it dominates the javascript transpiling community.

Let’s get it setup in our project before I talk about it too much.

So first thing’s first, create a .babelrc file in our project root and install babel-core.

yarn add babel-core
touch .babelrc

.babelrc will contain the rules babel live by. What features of javascript do we want to use with this project?

What a strange and interesting question. The babel website will be crucial to look up tools you may need. The community is large and prolific, having covered all of javascript’s various specifications, they went on to write transpiling plugins for various flavors and new languages. All compiling to any other flavor of javascript.

So for example, let's say we want to use those nifty arrow functions in ES6. In main.js add:

var a = () => {
  console.log("Hello from the future!")

Babel provides a plugin for that. Let’s install that and add the plugin to our .babelrc.

In terminal:

yarn add babel-plugin-transform-es2015-arrow-functions babel-cli

In .babelrc

  "plugins": ["transform-es2015-arrow-functions"]

In terminal:

yarn babel src/main.js

Note: We use yarn in front of the babel binary (if we're using yarn) to get our package dependencies right.

And the output speaks for itself:

Babel CLI output

Babel Integration with Webpack

So that's from the command line. In our webpack config, let’s add the babel loader to our rules array.

  test: /\.js$/,
  exclude: /node_modules/,
  use: [{
    loader: "babel-loader"

We tell it to exclude node_modules as they are already ES5 and we don't want babel transpiling everything, very slow. Just our project code.

When we restart with yarn start we now have the full power of Babel at our disposal. We can extend our javascript with any and all new ideas from the javascript community.

In Sum

In the case of transformations that javascript can handle, no polyfills or additional libraries are needed to rewrite the code, so the file size doesn’t change much.

Discover and read more posts from Lawrence Whiteside
get started