Devin Roché

How to setup babel to compile ES6 code into ES5

I’m constantly having to look up how to setup babel to convert es6 to es5 so I figured I would write a post to help myself and possibly others!

Project Setup

Ok so lets create a project directory and initialize our package.json

mkdir babel-dummy-dir
cd babel-dummy-dir
npm init

Now lets install the needed babel packages.

npm install --save-dev babel-cli babel-preset-env

babel-preset-env is the main library that we use to convert our ES6 to ES5.

Now let’s create our src folder!

mkdir src
cd src && touch index.js

Start Hacking

Now we can enter some fancy ES6 code into our index.js. I’ll be using the code below.

class Dog {
  constructor (name) {
    this.name = name;
  }

  static bark(){
    console.log('woof');
  }
}

Dog.bark();

Now we are ready to run our program, but first we need to go into our package.json and add our build command. We can add two commands to our package!

"build": "babel src -d build",
"start": "node build/index.js"

Build & Run

We are ready to run our code now. Lets call our build command with npm run build, this will build all the files in our src directory into our build directory. Now it’s time to run our ES5 code! Enter npm start and you should see something like the output below…

babel-dummy@1.0.0 start .../babel-dummy
node build/index.js

woof

There we have it, we compiled our ES6 code into ES5 using babel!


twitter |github