Saturday 22 December 2018

What is Transpilling in JavaScript?

Transpillers are the tools that convert the source code written in one language to other language.

Why Transpillers?
EcmaScript6 is released in 2015, but not all the browsers are compatible with EcmaScript6 standard. When you see the browsers compatibility matrix related to EcmaScript6, it looks like below.



Refer below url to get more details.

To solve this incompatibility problems, there are transpillers available to convert the code written in ES6 (EcmaScript-6) to ES5(EcmaScript-5). There are many transpilling tools available in the market. Following are some of the popular transpilling tools.
a.   Babel
b.   Closure
c.   Traceur

Introduction to Babel
Babel is one of the most popular transpilling tool to convert EcmaScript-6 code to EcmaScript 5 code.

As you see below figure, Babel takes ES-6 code as input and give ES-5 code as output.


Let us develop a html page, that user EcmaScript-6 features.

HelloWorld.html
<!DOCTYPE html>
<html>
<body>

<script type="text/javascript">
 function sayHello(firstName="Krishna", lastName="Gurram"){
  document.write("<h2>Hello Mr." + firstName + ","+lastName+"</h2>");
 }
 sayHello();
</script>

</body>
</html>

As you see above page, I am using default parameters feature of EcmaScript6 standard. As you see I define function sayHello, that takes "Krishna" as default argument for firstName and "Gurram" as default argument for lastName. If you call the function sayHello() without arguments, then default values are used.

Open HelloWorld.html page in internet explorer and inspect the page, you can see below kind of error messages in console.


Since Internet Explorer is not supporting EcmaScript-6 default arguments feature, it is unable to understand the code snippet. We can solve this problem using babel transpiller. Rewrite HelloWorld.html application like below.

HelloWorld.html
<!DOCTYPE html>
<html>
<body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.js"> </script>

<script type="text/babel">
 function sayHello(firstName="Krishna", lastName="Gurram"){
  document.write("<h2>Hello Mr." + firstName + ","+lastName+"</h2>");
 }
 sayHello();
</script>

</body>
</html>

As you see above snippet,
a.   I added babel.js script file to the HelloWorld application.
b.   Instead of <script type="text/javascript">, I used <script type="text/babel">

Open HelloWorld.html in browser, you can see below message in console.




Previous                                                 Next                                                 Home

No comments:

Post a Comment