What is Transpiling?

Although we write our code in ES6, some of the browsers may not support it or may not support the whole ES6 code. And the only way to ensure that your ES6 code work is to convert it into the ES5 code, and this process is called transpiling. And one the most famous tool for this process is Babel.

Let us say we are writing a code in ES6 format just to calculate the mean of three numbers

const getMean = (x=1, y=2, z=3) => {
 var mean = (x + y + z) /3;
 return mean;
}

after running this code in the transpiler we will get

"use strict";

var getMean = function getMean() {
 var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
 var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
 var z = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 3;

 var mean = (x + y + z) / 3;

 return mean;
};


it uses "add strict" declaration to run this script in the script mode and all the variable are specifically defined using the arguments array.
Note: any js file can be transpiled with the following way

<script src= "https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.js" > </script>
<script src= "yourFile.js" type="text/babel" > </script>
and make sure that your js file is served from the server

Happy Coding

Comments

Popular posts from this blog

Functional Programming in Java - Part 1

Akka Actors in Java - Part 1

sealed keyword in Scala