DEV Community

Devin Roche
Devin Roche

Posted on

How to set up Babel 101

I'm constantly having to look up how to set up babel to convert ES6 to ES5 so I figured I would write a post to help myself and possibly others!

Project Set Up

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

mkdir babel-dummy-dir
npm init
Enter fullscreen mode Exit fullscreen mode

Now lets install the needed babel packages.

npm install --save-dev babel-cli babel-preset-env
Enter fullscreen mode Exit fullscreen mode

babel-preset-env is the main library that we use to convert our ES6 to ES5. It works by having version mappings which allows babel to take our ES6 features and find ES5 features.

After that has finished we need to create our .babelrc file in the root directory.

touch .babelrc
Enter fullscreen mode Exit fullscreen mode

Then we need to add the following.

{
  "presets": ["env"]
}
Enter fullscreen mode Exit fullscreen mode

Now let's create our src folder!

mkdir src
cd src && touch index.js
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)