Transpile ES6 code to ES5 using Babel

After reading this https://jogendras.wordpress.com/2017/07/06/what-is-es-5-es-6-or-es2015-and-typescript I hope now we know what actually is ECMAScript or ES-5, ES-6 or ES-2015.

ECMAScript 6, also known as ECMAScript 2015, is the latest version of the ECMAScript standard. ES6 is a significant update to the language, and the first update to the language since ES5 was standardized in 2009. Implementation of these features in major JavaScript engines is underway now

As mentioned that all browsers are currently not supported ES6 features so we would need a transpiler like BABEL (Babel is a compiler. At a high level, it has 3 stages that it runs code in: parsing, transforming, and generation) or TRACEUR to convert ES6 code to ES5 so that all browsers can understand and execute ES6 code.

System Setup –

We can use babel built-in CLI or any build systems like grunt, gulp or webpack to load babel transpiler. Lets do system setup with both built ins CLI and gulp to convert ES6 code to ES5. I am assuming you have already installed Node in your machine 🙂

  1. Using Babel CLI :

    Below are the steps to create a sample application (ES6_to_ES5_using_babel) using ES6 code.

    • Create a folder at your preferred location. In my case this is –D:\git_public\es6_to_es5_using_babel/using-babel-cli
    • Create a JavaScript file index.js with some ES6 code like below. I am putting all my ES6 code files into scripts folder.
      let greet = () => {
              alert(‘Hello, Welcome to ES-6 world!’);
      };
    • Open command prompt and type below commands-
      • cd D:\git_public\es6_to_es5_using_babel\using-babel-cli
      • > npm init
        • This will ask you a bunch of questions, and then write a package.json file for you
      • > npm install babel-cli –save-dev
        •  It will install the babel-cli as local package and save it in the package.json file. The local package installs the commands to the node_modules/.bin folder and these commands can be accessed using the scripts section of the package.json file.
      • Add the below code in the package.json file to run babel command to convert index.js file into ES5 code. We can also configure babel to compile all files at once or with many more options as mentioned here
        “scripts”: {
             “transpile”: “babel scripts/index.js –out-file scripts/index-transpiled.js”
        },
      • All set, now run the below command to transpile code-
        > npm run transpile
      • YAY… index-transpiled.js file is created under scripts folder. Now see what is in this file. Is this same as ES6 code ? Yes, babel did not transpile our code to ES5. Why? because Babel doesn’t do anything. It basically acts like const babel = code => code; by parsing the code and then generating the same code back out again. We will need to add some plugins for Babel to do anything (they affect the 2nd stage i.e transformation).
      • As currently we are using ES6 only arrow function in our code so to understand lets install the only plugin to convert arrow function to ES5 compatible code.
      • > npm install babel-plugin-transform-es2015-arrow-functions -D
        • We can make it available to babel through its configuration file i.e .babelrc (recommended) or directly in the package.json file
      • So create .babelrc file in the root directory and add required plugins
        {
            “plugins”: [“transform-es2015-arrow-functions”]
        }
      • Now again run the command-
        >  npm run transpile
      • Now see in the transpiled file. YAY…  code is converted to ES5 code-
        let greet = function () {
             alert(‘Hello, Welcome to ES-6 world!’);
        };
      • Now, as there are many features in the ES6 and it would be bit difficult to install plugin for each as we did for arrow function. How to solve this problem so we can use all ES6 features instead of installing plugin/package for each feature? To solve such kind of problems presets comes in the picture. Presets are sharable configurations or simply an array of plugins. If we will install a preset then it will automatically install all dependent plugins/packages. 
      • To compile code from ES6 to ES5 we haveES2015 preset which have all required plugins. So lets uninstall the plugin for arrow function which we installed earlier and install ES2015 preset.
      • > npm uninstall babel-plugin-transform-es2015-arrow-functions -D
      • > npm install babel-preset-es2015 -D
      • Now make all the ES6 plugins available to babel via .babelrc config file in the form on presets.

        {
             “presets”: [“es2015”]
        }
      • Now you are all set to use any ES6 feature using babel cli…. Source code can be found here…. https://github.com/sjogendras/es6_to_es5_using_babel
  2. Using Gulp –

    Gulp and Grunt are widely used as task runners in front-end applications. They make it easy to configure and run tasks to perform many of the tasks that we otherwise had to perform manually. Babel has packages for both Grunt and Gulp that can be used to achieve everything that is achievable through the commands that we saw in using babel-cli.
    First things first, let’s install the required npm packages to perform Babel’s tasks with Gulp and to use require.js with Gulp. Following are the packages we need-

    • > npm init
    • > npm install gulp -g

      • Installing gulp globally so we can run gulp command directly from command prompt instead of writing script in package.json.
    • > npm install gulp-babel -D
    • > npm install babel-core -D
    • > npm install babel-preset-es2015 -D
    • Create gulpfile.js file
      var gulp = require(“gulp”);
      var babel = require(“gulp-babel”);
      gulp.task(“transpile“, function() {
         returngulp.src(“src/index.js”)
            .pipe(babel())
            .pipe(gulp.dest(“dist”));
      });
    • Create .babelrc file
      {
           “presets”: [“es2015”]
      }
    • > gulp transpile
    • YAY…. ES6 code transpiled and put into the dist folder.
    • https://github.com/sjogendras/es6_to_es5_using_babel

Programming is Easy…

Advertisements

One thought on “Transpile ES6 code to ES5 using Babel

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s