BabelJS – ES6 Code Execution ”; Previous Next 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 like 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 compiling 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()); Chrome Output Firefox Browser Output IE Browser Output Print Page Previous Next Advertisements ”;
Category: babeljs
Aug
10