Using babel convert ES2015 (ES6) code to ES5

ECMAScript 2015 (or ES6) is the next big thing and front end developers should start learning it now, not later. So you want to start using ES6 but are worried about browser support and backwards compatibility for your application? Not to worry, Babel can help us there.

Babel  cross-compile your JavaScript back to ES5 compatible code for older browsers, meaning there’s no reason to put off learning about it.

So let’s get started…

1. Install Babel as Dev Dependency

You need to install babel packages so the first thing that we are going to do is run this command:

  • $ npm install -D babel-cli

so what babel-cli means ? this is going to install the package of babel that include the commands tools and after that we need to run this code:

  • $ npm install -D babel-preset-env

Without any configuration options, babel-preset-env behaves exactly the same as babel-preset-latest (or babel-preset-es2015, babel-preset-es2016, and babel-preset-es2017 together). This is going to permit that babel maps for older version to transpile the code for us

2. Write ES6 Code

Now write some ES6 code. I suggest you would  house your JavaScript files in a folder, such as src or javascript. I’m going to make an example file:

// src/example.js
class Hello {
  static world() {
    console.log('Hello, World!');
  }
}
Hello.world();

ok we already have babel in our project what’s next ? 

We need to create package.json file.

3. npm init

It will ask couple of questions needed for generating the file. After that you’ll have a package.json file created in your directory.

Now we have our babel packages installed and we just created our package.json file that is going to contain all the information about our project so now we can start setting up babel in our project.

4. Create .babelrc

The first thing that we are going to do is to create a file called .babelrc in our root project and inside write this code:

{
"presets": ["env"]
}

5. Create a npm build command

Go to your package.json file where we’ll create a npm build script using the babel command. The babel command takes two arguments: the path to your ES6 code and a path to where you want your ES5 code to go.

If you have all your JavaScript code housed in a directory, then you can add the -d flag to the command to tell Babel for look for directories instead of files. For my example, I have my JavaScript code in my src directory but want my ES5 code to be put in a build directory.

// package.json
...
"scripts": {
  "build": "babel src -d build",
},
...

So now we are ready to use babel in our project and transpile javascript from ES6 to ES5 we just need to use this code in our terminal to make it work:

  • $ npm run build

You should see your converted JavaScript files in a build directory.