DotNetCurry Logo

Transpiling ES6 modules to ES5 using Babel

Posted by: Ravi Kiran , on 7/10/2016, in Category HTML5 & JavaScript
Views: 11316
Abstract: We can use Babel directly or with a task manager like Gulp to transpile ES6 modules into ES5. This uses Babel to transpile ES6 code to ES5

ECMAScript 2015 (also known as ES 2015 or ES6) is the current version of JavaScript, and its biggest update till date. It comes with a number of language improvements and API updates to make JavaScript developers more productive. The specification of the language was frozen in June 2015. Browsers have started implementing the new features, although they still need some time to implement all the features. Meanwhile, as we saw in previous articles on ES6, transpilers have filled in the gaps and have allowed us to use these new features, till the browsers implement them all.

This article is published from the DNC Magazine for Developers and ArchitectsDownload this magazine from here [Zip PDF] or Subscribe to this magazine for FREE and download all previous and current editions

There are a number of transpilers that convert the ES6 code to browser readable ES5 code. The most popular one these days is Babel. It was named 6to5 earlier, but then got renamed to Babel to make the name generic. The other popular alternatives are Traceur from Google and TypeScript, the typed JavaScript language from Microsoft.

In this article, we will use Babel to transpile ES6 code to ES5.

The reason for choosing Babel is, amongst all other transpilers, Babel supports the most number of ES6 and ES7 features. The ES5 code it generates after transpiling the ES6 code, can easily be read and understood by any average JavaScript developer, as it doesn’t add any special variables or hacks in the converted code. In this article, we will see how to setup an environment and transpile the ES6 code into ES5 using Babel.

About the sample ES6 application

The sample used for this article is a simple application that uses GitHub’s REST API to fetch the list repos under a GitHub account and displays them in an HTML table. The application consists of three JavaScript files written in ES6 and they perform a different set of tasks for the application. The following figure shows the folder structure of the application:

es6-bable-structure

Figure 1: ES6 application folder structure

The file index.html is the starting point of this application. It has to load the JavaScript files to display the GitHub repos.

The following is the list of JavaScript files of the project and a brief description of the task they perform:

· gitHubSvc.js: Queries the GitHub REST API using jQuery and gets the list of repos under an organization

· uiPainter.js: Accepts the data that has to be presented and displays it in the target HTML element

· initialize.js: This files uses both of the above files and wires them up to the page

All of these files use the import/export syntax of the ES6 module system and they use ES6 features to achieve their tasks. You can check the code in ES6 folder of the sample on GitHub.

Transpiling using Babel

Babel can be used to transpile the JavaScript code through its command line interface (CLI) or can be used as part of the JavaScript build tools like npm scripts, Gulp and Grunt. We will see how to transpile using Babel through command line and using Gulp.

Using Babel CLI

To use Babel through command line from any folder in the system, we need to install the global npm package of Babel. The global package has to be used only to play around with the features of the tool. To use it in a project that is being built by a team of people, we should install it in the project. We will see both of these use cases.

Using Global Babel Package

To install Babel globally, we need to use the following command:

> npm install –g babel-cli

To check if Babel is installed properly, you can run the following command to check the version of Babel package installed on your system:

> babel –V

If this command is unsuccessful, you need to try installing Babel again. Once Babel is installed, we can use the command with different options to transpile the JavaScript code.

To transpile a single file, you can pass name of the file to the Babel command:

> babel script.js

This command transpiles the code in script.js file and displays result in the console. If you want to save the output of this command into a file, you need to use the --out-file option of the Babel command and provide a path of the target file.

> babel script.js --out-file script-transpiled.js

This command doesn’t convert the ES6 code to ES5. To do so, we need to install the ES2015 preset of Babel and make it available to Babel through its configuration file, .babelrc. Babel’s ES2015 preset contains all of the plugins required to convert every new API and feature of ES6 to its ES5 equivalent. You can see the list of plugins installed with the ES2015 preset on this page. The preset is an npm package, we can install it using the following command:

> npm install babel-preset-es2015 –save-dev

We need to store the configuration required for Babel in a file named .babelrc. The following JSON snippet shows how the preset has to be loaded:

{
  presets: ["es2015"]
}

If the application needs any other preset, we can mention it in the above array and Babel will automatically use them. Now the command will produce an ES5 equivalent of the ES6 code present in the script.js file.

Using Local Babel Package

If you want to use Babel through a local package and share it with your team, you need to install it as a local package and save it in the package.json file. We need both Babel and babel-cli packages to use the utility as a local package. The following command does this:

> npm install babel babel-cli --save-dev

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. We can register the command to transpile the JavaScript file under the scripts section as follows:

scripts: {
  “transpile”: “babel script.js --out-file script-transpiled.js”
}

We can invoke this script using the following command:

> npm run transpile

Now let’s start working on transpiling the sample code. If you want to follow along, download the folder GitHubRepos_before from the source code of this article and install the node modules. Once the installation is complete, follow the instructions discussed in the next section.

Transpiling ES6 Modules to AMD using CLI

Let’s transpile code of the sample application to ES5. We will discuss how to do it using the command line interface and then we will do the same thing using Gulp.

If you use the ES2015 preset and follow the process mentioned in the previous section to transpile the ES6 code, you will notice that the ES6 modules used in the files are converted into CommonJS style modules. CommonJS is a JavaScript module system designed by the open source developers at the CommonJS group. It provides the modules with the objects require and exports to import and export the modules respectively. It loads the modules synchronously and the objects exported from the other modules can be used in the consuming module. Visit the CommonJS wiki page to learn more about the module system.

The ES2015 preset includes the Babel plugin to convert the code into CommonJS style module system, so this plugin detects the presence of modules in the ES6 file and converts it into CommonJS module.

Alternatively, we can convert the ES6 modules into AMD, SystemJS or UMD modules by installing the corresponding Babel plugin and including it in the .babelrc file. The AMD (Asynchronous Module Definition) style module system defines a way to load the modules asynchronously. A module can use a set of other modules as its dependencies, and these modules are loaded asynchronously without waiting for the previous modules to finish. The module using these dependencies is executed once all of these modules are ready.

Let’s convert the ES6 modules into AMD style modules. The following command installs the npm package containing the plugin for this purpose:

> npm install babel-plugin-transform-es2015-modules-amd

We need to include it in the plugins section of the .babelrc file. Add a new file to the project and change its name to .babelrc. Paste the following snippet into it:

{
  "presets": ["es2015"],
  "plugins": ["transform-es2015-modules-amd"]
}

Now, running the following command will transpile the ES6 files into AMD style modules and store them in the dist/temp folder.

> babel ES6 –out-dir dist/temp

To load this code in the browser, we need a library that would help us in loading the AMD modules in the browser. Require.js is one of the libraries used to load AMD modules in the browser. It has to be installed using npm. The following command installs this library:

> npm install requirejs –save

Let’s transpile the modules in the application to AMD now. The following command does this for us:

> babel ES6 --out-dir dist

This command reads all the files under the ES6 folder, converts them to ES5 with AMD syntax and copies the resultant files into a folder named dist. In order to use this command repeatedly, we can store it in the scripts section of package.json.

"scripts": {
  "transpile-amd": " babel ES6 --out-dir dist"
}

This command can be invoked from the command line as follows:

> npm run transpile-amd

To load the converted files on browser and see them in action, we need to include the require.js library and ask it to load the first file of the application, which is initialize.js. For this, we need to add the following statement to the index.html file:

http://node_modules/requirejs/require.js

The data-main attribute in the above snippet is used to load the first AMD module. Every file is treated as a module, so this snippet loads the file initialize.js. As this file needs the other two files, require.js loads them asynchronously before running the code inside the module of the file initialize.js.

Run the application and you will see the page loading the list of projects by AngularJS team (I hard coded the organization as angular in the code).

transpiling-es6

Transpiling ES6 code using Gulp and Babel

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. Out of the two, I personally like Gulp for its API and the asynchronous approach.

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 the previous section.

Like Babel, if you want to use Gulp from anywhere on the system, then we need to install it globally using the following command:

> npm install -g gulp

Otherwise, we can use it from the local Gulp package as we did in case of Babel.

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:

· gulp: A local copy of gulp

· gulp-babel: This package enables us to use Babel in a Gulp task

We can install both of these packages using a single command, the command is shown below:

> npm install gulp gulp-babel --save-dev

Add a new file to the root folder of the project and name it gulpfile.js. Let’s get references of the npm packages we need in this file.

var gulp = require('gulp'),
babel = require('gulp-babel');

Before writing a task to transpile the code in the sample application, let’s understand how Babel works with Gulp. To transpile a file using Babel in Gulp, we need to load the file and pipe the Babel task into it. The following snippet demonstrates how an imaginary ES6 file named sample.js can be transpiled in a Gulp task:

gulp.task(‘transpile’, function(){
  return gulp.src([‘sample.js’])
.pipe(babel())
.pipe(gulp.dest(‘trasnpiled-sample.js’));
});

The above task transpiles the code in the file supplied and stores the resultant file in a file named transpiled-sample.js. As we invoked the Babel package without passing any values into it, it will use the configuration stored in the file .babelrc in the current folder. If it doesn’t find the file, the transpilation will happen according to babel’s default configuration. The above task can be invoked from the command line as follows:

> gulp transpile

We can pass Babel’s configuration to the task, instead of storing it in the .babelrc file. Remember not to mix them both, as at times it may result in some odd results, that are hard to spot and fix. The following snippet passes the configuration into the Babel task:

return gulp.src([‘sample.js’])
.pipe(babel({
  "presets": ["es2015"],
  "plugins": ["transform-es2015-modules-amd"]
}))
.pipe(gulp.dest(‘trasnpiled-sample.js’));

Now that we understood how to use Babel with Gulp, let’s write a Gulp task to transpile the files in the sample application. The task that we are going to write is similar to the sample task shown above; we just need to change the paths in it. The following snippet shows the task:

gulp.task('transpile', function () {
    return gulp.src(['ES6/*.js'])
        .pipe(babel())
        .pipe(gulp.dest('dist'));
});

We can run this task using the following command:

> gulp transpile

This command converts the ES6 files into ES5 files with AMD and copies the files into the dist folder. As we added reference of require.js library with the initial script to the HTML file in the previous section, we don’t need to make any changes. Run the application and you will see the same result as we saw in the last section.

Conclusion

The ES6 specification added a much-needed feature of Modules to the JavaScript language [http://www.dotnetcurry.com/javascript/1118/modules-in-ecmascript6]. Though they are not entirely supported by the browsers yet, transpilers like Babel help us in using them today. As we saw, we can use Babel directly or with a task manager like Gulp to convert the ES6 modules into AMD style modules. We can convert it to other types of modules as well.

Download the entire source code from GitHub at bit.ly/dncm24-transpile-es6

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Rabi Kiran (a.k.a. Ravi Kiran) is a developer working on Microsoft Technologies at Hyderabad. These days, he is spending his time on JavaScript frameworks like AngularJS, latest updates to JavaScript in ES6 and ES7, Web Components, Node.js and also on several Microsoft technologies including ASP.NET 5, SignalR and C#. He is an active blogger, an author at SitePoint and at DotNetCurry. He is rewarded with Microsoft MVP (Visual Studio and Dev Tools) and DZone MVB awards for his contribution to the community


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!