≡ Menu

How to Use Babel Javscript Compiler as Transpiler with Example Program

babel-logoBabel will transform your javascript code from one format (or version) to another.

In this regard, Babel is a transpiler.

A Transpiler is a compiler which will transform source code from one version/language to another version/language.

The latest version of Javascript implementation standard is ECMAScript ES7 (which is also known as ECMAScript 2016).

Prior to ES7, we had ES6 (ECMAScript 2015) and ES5.

The new ES7 standard will take some time to get full support from all modern browsers.

Since ES7 is not fully adopted yet, to be able to use this latest version of ECMAScript we need “Transpilers” to do the job.

The following are the two popular ECMAScript JavaScript Transpilers:

  • Babel
  • Traceur

In this tutorial, we’ll look at how to use Babel as a transpiler in the following three situations:

  1. Babel on client side (Non Node.js environments)
  2. Babel on server side (Node.js environments)
  3. Babel from Command Line using babel-cli

1. Babel On the Client Side (Non Node.js environments)

You can use babel-standalone to transpile ES6 to ES5 in a browser environment.

You just need to load the “babel-standalone” in your script as highlighted below and write the script you want to transpile, in script tag with type “text/babel” or “text/jsx”.

Babel will automatically compile and execute the script.

Let us create an example html file with ES6 to see how it works.

Create an html file and copy paste the following code and run it on any browser. This will display “Hello World” message on the browser.

<html>
  <head> 
    <title> Sample transpiling ES6 to ES5 </title>
  </head>
  <body>
    <div id="output"></div>
    <!-- Load Babel -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.18.1/babel.min.js"></script>
    <!-- Your custom script here -->
    <script type="text/babel">
      const getMessage = () => "Hello World";
      document.getElementById('output').innerHTML = getMessage();
    </script>
  </body>
</html>

In the above code:

  • We have the babel.min.js script included in the script tag.
  • For the script type, we’ve mentioned “text/babel”

The other way, is to go with apis exposed by “babel.min.js” to transform it using Babel object as highlighted in the following example.

In the following example “es2015” is passed as preset, so that babel gets to know, to which version of ECMAScript is this is to be transpiled. This is using babel-standlone.

As the name suggests, babel-standalone is a standalone build of Babel. This is used in the non-Node.js environments. For example, you can use the standalone version to do your initial development and testing locally on your browser. This standalone verion contains all the babel plugins and presets. You also have the option of including the babel-minify with the standlone version.

<html>
<head> 
  <title> Sample transpiling ES6 to ES5 </title>
</head>
<body>
  <div id="output"></div>
  <!-- Load Babel -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.18.1/babel.min.js"></script>
  <!-- Your custom script here -->
  <script type="text/javascript">
    var input = 'const getMessage = () => "Hello World";document.getElementById("output").innerHTML = getMessage();';
    var output = Babel.transform(input, { presets: ['es2015'] }).code;
    eval(output);
  </script>
</body>
</html>

2. Babel on Server Side (Node.js environment)

On the server side, we can use multiple types of build tools and there is a babel plugin for all of those.

Let us see how we can use babel with “gulp”, which is one of the widely used build tool currently.

If you are new to Node.js, you can install Node.js either using NPM command, or NodeSource, or from Binaries

First get into your project folder and run the following commands to install “gulp”, “gulp-babel” and its preset “babel-preset-latest”.

Here, “gulp-babel” is a gulp plugin for babel. As the name suggests, “babel-preset-latest” is a babel plugin needed to transform the code, as “gulp-babel” alone will only parse the code. Also, Presets allows us to mention the exact version in which you want to transpile the code.

This will give you a list of all official babel presets.

First, install the gulp-babel and babel-preset-latest using npm command.

npm init
npm install - -save-dev gulp gulp-babel babel-preset-latest

Next, create a file “app.js” in your project folder and copy paste the following ES6 sample code:

const getMessage = () => "Hello World";
document.getElementById('output').innerHTML = getMessage();

Next, create a gulpfile.js and copy paste the following code which is the basic gulp configuration for using babel with it.

var gulp = require("gulp");
var babel = require("gulp-babel");
gulp.task("default", function () {
  return gulp.src("./app.js")
    .pipe(babel())
    .pipe(gulp.dest("dist"));
});

If you are new to Gulp, read this to understand how Gulp can be used as Task Automation Tool and how to install Gulp.js.

Finally, we will have do the preset settings/configuration so that babel is able to know on which version, it is to be transformed.

This can be done in two ways. We need to create “.babelrc” file to do runtime configuration of the preset or we will have to modify the above script to mention the preset to be used as highlighted below.

var gulp = require("gulp");
var babel = require("gulp-babel");

gulp.task("default", function () {
  return gulp.src("./app.js")
    .pipe(babel({
        "presets": ["latest"]
    }))
    .pipe(gulp.dest("dist"));
});

As stated above you can also create a “.babelrc” file and add following json, to set it up:

{
  "presets": ["latest"]
}

From the project folder type “gulp” command and then open/check the file created in “dist” folder. You will find the ES6 code transpiled to ES5.

3. Babel from Command Line Interface (Babel CLI)

For this, we will need “babel-cli” package from npm repository.

Execute the following commands to create “package.json” and get the “babel-cli” installed.

npm init

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

Now to run it directly using cli, by using the following command to do the same task as we did in previous examples.
Please note that, we should also have “.babelrc” file as well in project folder, as configured earlier.

./node_modules/.bin/babel ./app.js -d dist

Alternatively you can also, open the “package.json” file and do the following configuration as highlighted, to run the “babel” command using “npm run”. Please note that we should also have “.babelrc” file as well in project folder, as configured earlier.

In the package.json, add the “scripts” section that is shown below, which will include the “transpile” section for babel.

{
  "name": "babel-test",
  "version": "1.0.0",
  "description": "This is a test done",
  "main": "app.js",	
  "dependencies": {},
  "devDependencies": {
    "babel-cli": "^6.18.0",
     "babel-preset":"^6.16.0"
  },
  "scripts": {
    "transpile": "babel ./app.js -d dist"
  },
  "repository": {
    "type": "git",
    "url": "NIL"
  },
  "keywords": [
    "NIL"
  ],
  "author": "Luke Issac",
  "license": "luke@thegeekstuff.com"
}

After doing the above configuration, you will have to type “npm run transpile” on CLI to get the task done. You can keep any keyword, instead of the word “transpile” in the highlighted area and use it like a command.

# npm run transpile

> babel-test@1.0.0 transpile /home/app/babel
> babel ./app.js -d dist

./app.js -> dist\app.js
Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book