- Babel is a compiler for next generation JavaScript.
- Babel js compiles the ES6+ features to ES5 code.
- We can find more information about Babel using following URL which points to the home page of Babel.
- In this demo, “We will Learn to install Babel and learn how to use it to test some ES6 feature”.
- Babel can be used with many tools for development like Browserify,WebPack and lot more.You can find the complete list in the following URL.
https://babeljs.io/docs/using-babel/
- Let’s install the Babel using Node Package Manager(NPM).Babel can be installed globally using npm install babel –g command.Babel can be installed locally using npm install babel –save-dev command.The following screenshot shows the terminal with Babel installation.
- We have created my-script-dev.js file contains the Code implementing ES6 Arrow operator feature.Babel will compile this file to generate my-script-build.js file.The code content of my-script-dev.js file is as follows.
var sayHello = (name) => { return "Hello: "+name; }; var result = sayHello("Sandeep"), message = document.createElement("H1"); message.innerText = result; document.body.appendChild(message);
- To demonstrate Babel compiler we have created NPM script in package.json file containing Babel my-script-dev.js –out-file my-script-build.js command.The following screenshot shows the terminal with NPM Babel compilation executed to generate my-script-build.js file.The content of package.json file is as follows.
{ "name": "BabelJSDemo", "version": "0.0.1", "description": "Babel demo", "scripts": { "make": "Babel my-script-dev.js --out-file my-script-build.js" }, "repository": { "type": "git" }, "author": "Sandeep", "license": "ISC", "devDependencies": { "babel": "^5.4.5" } }
- Now we can use npm run make command to generate the ES5 code in my-script-build.js file.The following screenshot shows the terminal with babel compilation.
- After successful run of above compilation it generate the my-script-build.js file.The code content of my-script-build.js file is as follows.
"use strict"; var sayHello = function sayHello(name) { return "Hello: " + name; }; var result = sayHello("Sandeep"), message = document.createElement("H1"); message.innerText = result; document.body.appendChild(message);
- The updated project structure looks like following screenshot.
- The index.html file uses the my-script-build.js file to show the output in browser.The content of index.html file is as follows.
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Babel JS Demo</title> </head> <body> <script src="my-script-build.js"></script> </body> </html>
- The output of index.html file is as follows.
- The demo code can be downloaded from following screenshot
https://github.com/saan1984/BabelJSDemo