- Traceur provides offline compilation of ES6 code to ES5 code for testing ES6 feature.
- In the previous post we learnt installing Traceur and installing traceur-runtime.js file using Bower.
- In this Demo, “We will learn to use traceur command to compile ES6 code to ES5 for ES6 Arrow operator”.
- For this demo we have created 2 directories es6dev and build. We have also created demo.html file for demonstrating ES6 feature.The es6dev directory will have ES6 code and build directory will have compiled ES5 code for respective JavaScript file.
- The following screenshot shows the updated directory structure of our application containing bower_components,es6dev,build and demo.html files.
- Now we can write a code based on ES6 Arrow operator(=>).The es6-arrow.js script file contains the use of Arrow function.In the es6-arrow.js file contains a declaration of sayHello() method which takes a string and prints a message in the console.The following code shows the content of es6dev/es6-arrow.js file:
var sayHello = (name) =>{
console.log("Hello ",name);
};
sayHello("Sandeep")
- Now we can compile the code of es6-arrow.js file using traceur compilation.The following screenshot shows the terminal with traceur compilation where source is es6dev/es6-arrow.js file and destination is build/es6-arrow.js file.
- After successful compilation of Traceur the code is converted to ES5 and found in build/es6-arrow.js file.The following code shows the converted ES5 version of es6-arrow.js file.
System.registerModule("../es6dev/es6-arrow.js", [], function() {
"use strict";
var __moduleName = "../es6dev/es6-arrow.js";
var sayHello = (function(name) {
console.log("Hello ", name);
});
sayHello("Sandeep");
return {};
});
System.get("../es6dev/es6-arrow.js" + '');
- Now we can use es6-arrow.js file inside demo.html file.The following code shows the demo.html file.
<!DOCTYPE html>
<html>
<head lang="en">
<title>Traceur Compilation</title>
<script src="bower_components/traceur-runtime/traceur-runtime.min.js"></script>
</head>
<body>
<script src="build/es6-arrow.js"></script>
</body>
</html>
- The following screenshot shows the output of the demo.html file in the chrome console.
- The output of the above code can be found in below es6 fiddle: