- Working with Babel and JSX
- Working with Babel and Webpack
- BabelJs - Babel Presets
- BabelJs - Babel CLI
- BabelJs - Babel Polyfill
- BabelJs - Babel Plugins
- Transpile ES8 features to ES5
- Transpile ES7 features to ES5
- Transpile ES6 Modules to ES5
- Transpile ES6 features to ES5
- BabelJs - Project Setup Using Babel 7
- BabelJs - Project setup using Babel 6
- BabelJs - ES6 Code Execution
- BabelJs - CLI
- BabelJs - Environment Setup
- BabelJs - Overview
- BabelJs - Home
BabelJs Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
BabelJS - ES6 Code Execution
BabelJS is a JavaScript transpiler, which converts new features added to JavaScript into ES5 or to react based on the preset or plugin given. ES5 is one of the oldest form of JavaScript and is supported to run on new and old browsers without any issues. In most of the examples in this tutorial, we have transpiled the code to ES5.
We have seen many features pke arrow functions, classes, promises, generators, async functions, etc. added to ES6, ES7 and ES8. When any of the newly added features are used in old browsers, it throws errors. BabelJS helps in compipng the code, which is backward compatible with older browsers. We have seen that ES5 works perfectly fine on older browsers without any issues. So considering the project environment details, if it is required to be running on older browsers, we can use any new feature in our project and compile the code to ES5 using babeljs, and use it any browsers without any issues.
Let us consider the following example to understand this.
Example
<!DOCTYPE html> <html> <head> <title>BabelJs Testing</title> </head> <body> <script type="text/javascript" src="index.js"></script> </body> </html>
index.js file
var _foo = () => { return "Hello World" }; alert(_foo());
Output
When we run the above html in the Chrome browser, we get the following output −
When the HTML is run in Firefox, it generates the following output −
And when the same HTML is run in Internet Explorer, it generates the following syntax error −
We have used the ES6 Arrow function; the same does not work on all browsers as seen above. To get this working, we have BabelJS to compile the code to ES5 and use it in all browsers.
Will compile the js file to es5 using babeljs and check again in the browsers.
In html file, we will use index_new.js as shown below −
<!DOCTYPE html> <html> <head> <title>BabelJs Testing</title> </head> <body> <script type="text/javascript" src="index_new.js"></script> </body> </html>
index_new.js
"use strict"; var _foo = function _foo() { return "Hello World"; }; alert(_foo());