BabelJS – Quick Guide ”; Previous Next BabelJS – Overview BabelJS is a JavaScript transpiler which transpiles new features into old standard. With this, the features can be run on both old and new browsers, hassle-free. An Australian developer, Sebastian McKenzie started BabelJS. Why BabelJS? JavaScript is the language that the browser understands. We use different browsers to run our applications − Chrome, Firefox, Internet Explorer, Microsoft Edge, Opera, UC browser etc. ECMA Script is the JavaScript language specification; the ECMA Script 2015 ES6 is the stable version which works fine in all new and old browsers. After ES5, we have had ES6, ES7, and ES8. ES6 released with a lot of new features which are not fully supported by all browsers. The same applies to ES7, ES8 and ESNext (next version of ECMA Script). It is now uncertain when it will be possible for all browsers to be compatible with all the ES versions that released. Incase we plan to use ES6 or ES7 or ES8 features to write our code it will tend to break in some old browsers because of lack of support of the new changes. Therefore, if we want to use new features of ECMA Script in our code and want to run it on all possible browsers available, we need a tool that will compile our final code in ES5. Babel does the same and it is called a transpiler that transpiles the code in the ECMA Script version that we want. It has features like presets and plugins, which configure the ECMA version we need to transpile our code. With Babel, developers can write their code using the new features in JavaScript. The users can get the codes transpiled using Babel; the codes can later be used in any browsers without any issues. The following table lists down the features available in ES6, ES7 and ES8 − Features ECMA Script version Let + Const ES6 Arrow Functions ES6 Classes ES6 Promises ES6 Generators ES6 Iterators ES6 Modules ES6 Destructuring ES6 Template Literals ES6 Enhanced Object ES6 Default, Rest & Spread Properties ES6 Async – Await ES7 Exponentiation Operator ES7 Array.prototype.includes() ES7 String Padding ES8 BabelJS manages the following two parts − transpiling polyfilling What is Babel-Transpiler? Babel-transpiler converts the syntax of modern JavaScript into a form, which can be easily understood by older browsers. For example, arrow function, const, let classes will be converted to function, var, etc. Here the syntax, i.e., the arrow function is converted to a normal function keeping the functionality same in both the cases. What is Babel-polyfill? There are new features added in JavaScript like promises, maps and includes. The features can be used on array; the same, when used and transpiled using babel will not get converted. In case the new feature is a method or object, we need to use Babel-polyfill along with transpiling to make it work on older browsers. Here is the list of ECMA Script features available in JavaScript, which can be transpiled and polyfilled − Classes Decorators Const Modules Destructing Default parameters Computed property names Object rest/spread Async functions Arrow functions Rest parameters Spread Template Literals ECMA Script features that can be polyfilled − Promises Map Set Symbol Weakmap Weakset includess Array.from, Array.of,Array#find,Array.buffer, Array#findIndex Object.assign,Object.entries,Object.values Features of BabelJS In this section, we will learn about the different features of BabelJS. Following are the most important core features of BabelJS − Babel-Plugins Plugins and Presets are config details for Babel to transpile the code. Babel supports a number of plugins, which can be used individually, if we know the environment in which the code will execute. Babel-Presets Babel presets are a set of plugins, i.e., config details to the babel-transpiler that instruct Babel to transpile in a specific mode. We need to use presets, which has the environment in which we want the code to be converted. For example, es2015 preset will convert the code to es5. Babel-Polyfills There are some features like methods and objects, which cannot be transpiled. At such instances, we can make use of babel-polyfill to facilitate the use of features in any browser. Let us consider the example of promises; for the feature to work in older browsers, we need to use polyfills. Babel-Polyfills Babel-cli comes with a bunch of commands where the code can be easily compiled on the command line. It also has features like plugins and presets to be used along with the command making it easy to transpile the code at one go. Advantages of using BabelJS In this section, we will learn about the different advantages associated with the use of BabelJS − BabelJS provides backward compatibility to all the newly added features to JavaScript and can be used in any browsers. BabelJS has the ability to transpile to take the next upcoming version of JavaScript – ES6, ES7, ESNext, etc. BabelJS can be used along with gulp, webpack, flow, react, typescript, etc. making it very powerful and can be used with big project making developer’s life easy. BabelJS also works along with react JSX syntax and can be compiled in JSX form. BabelJS has support for plugins, polyfills, babel-cli that makes it easy to work with big
Category: babeljs
BabelJs – Home
BabelJS Tutorial PDF Version Quick Guide Resources Job Search Discussion BabelJS is a JavaScript transpiler which transpiles new features into old standard. With this, the features can be run on both old and new browsers, hassle-free. Babeljs comes with a wide range of features in the form of plugins, presets, polyfills, etc. In short, Babeljs is a toolset which has all the required tools available with it and which helps the developers to use all the current features available in ECMA Script and yet not worry how it will be supported on browsers. Audience This tutorial is designed for software programmers who want to learn the basics of BabelJS and its programming concepts in simple and easy ways. This tutorial will give you enough understanding on various functionalities of BabelJS with suitable examples. Prerequisites Before proceeding with this tutorial, you should have a basic understanding of JavaScript. Print Page Previous Next Advertisements ”;
BabelJS – Transpile ES7 features to ES5 ”; Previous Next In this chapter, we will learn how to transpile ES7 features to ES5. ECMA Script 7 has the following new features added to it − Async-Await Exponentiation Operator Array.prototype.includes() We will compile them to ES5 using babeljs. Depending on your project requirements, it is also possible to compile the code in any ecma version ie ES7 to ES6 or ES7 to ES5. Since ES5 version is the most stable and works fine on all modern and old browsers, we will compile the code to ES5. Async-Await Async is an asynchronous function, which returns an implicit promise. The promise is either resolved or rejected. Async function is same as a normal standard function. The function can have await expression which pauses the execution till it returns a promise and once it gets it, the execution continues. Await will only work if the function is async. Here is a working example on async and await. Example let timer = () => { return new Promise(resolve => { setTimeout(() => { resolve(“Promise resolved after 5 seconds”); }, 5000); }); }; let out = async () => { let msg = await timer(); console.log(msg); console.log(“hello after await”); }; out(); Output Promise resolved after 5 seconds hello after await The await expression is added before the timer function is called. The timer function will return the promise after 5 seconds. So await will halt the execution until the promise on timer function is resolved or rejected and later continue. Let us now transpile the above code to ES5 using babel. ES7 – Async-Await let timer = () => { return new Promise(resolve => { setTimeout(() => { resolve(“Promise resolved after 5 seconds”); }, 5000); }); }; let out = async () => { let msg = await timer(); console.log(msg); console.log(“hello after await”); }; out(); command npx babel asyncawait.js –out-file asyncawait_es5.js BabelJS – ES5 “use strict”; var timer = function timer() { return new Promise(function (resolve) { setTimeout(function () { resolve(“Promise resolved after 5 seconds”); }, 5000); }); }; var out = async function out() { var msg = await timer(); console.log(msg); console.log(“hello after await”); }; out(); Babeljs does not compile object or methods; so here promises used will not be transpiled and will be shown as it is. To support promises on old browsers, we need to add code, which will have support for promises. For now, let us install babel-polyfill as follows − npm install –save babel-polyfill It should be saved as a dependency and not dev-dependency. To run the code in the browser, we will use the polyfill file from node_modulesbabel-polyfilldistpolyfill.min.js and call it using the script tag as shown below − <!DOCTYPE html> <html> <head> <title>BabelJs Testing</title> </head> <body> <script src=”node_modulesbabel-polyfilldistpolyfill.min.js” type=”text/javascript”></script> <script type=”text/javascript” src=”aynscawait_es5.js”></script> </body> </html> When you run the above test page, you will see the output in the console as shown below Exponentiation Operator ** is the operator used for exponentiation in ES7. Following example shows the working of the same in ES7 and the code is transpiled using babeljs. Example let sqr = 9 ** 2; console.log(sqr); Output 81 ES6 – Exponentiation let sqr = 9 ** 2; console.log(sqr); To transpile the exponentiation operator, we need to install a plugin to be installed as follows − command npm install –save-dev babel-plugin-transform-exponentiation-operator Add the plugin details to .babelrc file as follows − { “presets”:[ “es2015” ], “plugins”: [“transform-exponentiation-operator”] } command npx babel exponeniation.js –out-file exponeniation_es5.js BabelJS – ES5 “use strict”; var sqr = Math.pow(9, 2); console.log(sqr); Array.prototype.includes() This feature gives true if the element passed to it is present in the array and false if otherwise. Example let arr1 = [10, 6, 3, 9, 17]; console.log(arr1.includes(9)); let names = [”Siya”, ”Tom”, ”Jerry”, ”Bean”, ”Ben”]; console.log(names.includes(”Tom”)); console.log(names.includes(”Be”)); Output true true false We have to use babel-polyfill again here as includes is a method on an array and it will not get transpiled. We need additional step to include polyfill to make it work in older browsers. ES6 – array.includes let arr1 = [10, 6, 3, 9, 17]; console.log(arr1.includes(9)); let names = [”Siya”, ”Tom”, ”Jerry”, ”Bean”, ”Ben”]; console.log(names.includes(”Tom”)); console.log(names.includes(”Be”)); command npx babel array_include.js –out-file array_include_es5.js Babel-ES5 ”use strict”; var arr1 = [10, 6, 3, 9, 17]; console.log(arr1.includes(9)); var names = [”Siya”, ”Tom”, ”Jerry”, ”Bean”, ”Ben”]; console.log(names.includes(”Tom”)); console.log(names.includes(”Be”)); To test it in older browser, we need to use polyfill as shown below − <!DOCTYPE html> <html> <head> <title>BabelJs Testing</title> </head> <body> <script src=”node_modulesbabel-polyfilldistpolyfill.min.js” type=”text/javascript”></script> <script type=”text/javascript” src=”array_include_es5.js”></script> </body> </html> Output Print Page Previous Next Advertisements ”;
BabelJs – Environment Setup
BabelJS – Environment Setup ”; Previous Next In this section, we will learn how to set up the environment for BabelJS. To work with BabelJS we need following setup − NodeJS Npm Babel-CLI Babel-Preset IDE for writing code NodeJS To check if nodejs is installed on your system, type node –v in the terminal. This will help you see the version of nodejs currently installed on your system. If it does not print anything, install nodejs on your system. To install nodejs, go to the homepage https://nodejs.org/en/download/ of nodejs and install the package based on your OS. The following screenshot shows the download page of nodejs − Based on your OS, install the required package. Once nodejs is installed, npm will also be installed along with it. To check if npm is installed or not, type npm –v in the terminal. It should display the version of the npm. Print Page Previous Next Advertisements ”;
BabelJS – Transpile ES6 features to ES5 ”; Previous Next In this chapter, we will see the features added to ES6. We will also learn how to compile the features to ES5 using BabelJS. Following are the various ES6 features that we will discuss in this chapter − Let + Const Arrow Functions Classes Promises Generators Destructuring Iterators Template Literalst Enhanced Object Default, Rest & Spread Properties Let + Const Let declares a block scope local variable in JavaScript. Consider the following example to understand the use of let. Example let a = 1; if (a == 1) { let a = 2; console.log(a); } console.log(a); Output 2 1 The reason the first console prints 2 is because a is declared again using let and will be available only in the if block. Any variable declared using let is just available within the declared block. We have declared variable a twice using let, but it does not overwrite the value of a. This is the difference between var and let keywords. When you declare variable using var, the variable will be available within the scope of the function or if declared will act like a global variable. Incase a variable is declared with let, the variable is available within the block scope. If declared inside the if statement, it will be available only within the if block. The same applies to switch, for-loop, etc. We will now see the code conversion in ES5 using babeljs. Let us run the following command to convert the code − npx babel let.js –out-file let_es5.js The output from es6 to es5 for the let keyword is as follows − Let using ES6 let a = 1; if (a == 1) { let a = 2; console.log(a); } console.log(a); Transpiled using babel to ES5 “use strict”; var a = 1; if (a == 1) { var _a = 2; console.log(_a); } console.log(a); If you see the ES5 code the let keyword is replaced with the var keyword. Also the variable inside the if block is renamed to _a to have the same effect as when declared with the let keyword. Const In this section, we will learn about the working of const keyword in ES6 and ES5. Const keyword is also available within the scope; and if outside, it will throw an error. The value of const declared variable cannot be changed once assigned. Let us consider the following example to understand how const keyword is used. Example let a =1; if (a == 1) { const age = 10; } console.log(age); Output Uncaught ReferenceError: age is not defined at :5:13 The above output throws an error as the const age is defined inside the if block and is available within the if block. We will understand the conversion to ES5 using BabelJS. ES6 let a =1; if (a == 1) { const age = 10; } console.log(age); Command npx babel const.js –out-file const_es5.js Transpiled to ES6 Using BabelJS “use strict”; var a = 1; if (a == 1) { var _age = 10; } console.log(age); Incase of ES5, const keyword is replaced with the var keyword as shown above. Arrow Functions An Arrow function has a shorter syntax in comparison to the variable expression. it is also called the fat arrow function or lambda function. The function does not have its own this property. In this function, the keyword function is omitted. Example var add = (x,y) => { return x+y; } var k = add(3,6); console.log(k); Output 9 Using BabelJS, we will transpile the above code to ES5. ES6 – Arrow function var add = (x,y) => { return x+y; } var k = add(3,6); console.log(k); Command npx babel arrowfunction.js –out-file arrowfunction_es5.js BabelJS – ES5 Using Babel the arrow function is converted to variable expression function as shown below. “use strict”; var add = function add(x, y) { return x + y; }; var k = add(3, 6); console.log(k); Classes ES6 comes with the new Classes feature. Classes are similar to the prototype based inheritance available in ES5.The class keyword is used to define the class. Classes are like special functions and have similarities like function expression. It has a constructor, which is called inside the class. Example class Person { constructor(fname, lname, age, address) { this.fname = fname; this.lname = lname; this.age = age; this.address = address; } get fullname() { return this.fname +”-“+this.lname; } } var a = new Person(“Siya”, “Kapoor”, “15”, “Mumbai”); var persondet = a.fullname; Output Siya-Kapoor ES6 – Classes class Person { constructor(fname, lname, age, address) { this.fname = fname; this.lname = lname; this.age = age; this.address = address; } get fullname() { return this.fname +”-“+this.lname; } } var a = new Person(“Siya”, “Kapoor”, “15”, “Mumbai”); var persondet = a.fullname; Command npx babel class.js –out-file class_es5.js BabelJS – ES5 There is extra code added using babeljs to get the functionality working for classes same as in ES5.BabelJs makes sure the functionality works same as it would have done in ES6. “use strict”; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (“value” in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(“Cannot call a class as a function”); } } var Person = function () { function Person(fname, lname, age, address) { _classCallCheck(this, Person); this.fname = fname; this.lname = lname; this.age = age; this.address = address; } _createClass(Person, [{ key: “fullname”, get: function get() { return this.fname + “-” + this.lname; } }]); return Person; }(); var a = new Person(“Siya”, “Kapoor”, “15”, “Mumbai”); var persondet = a.fullname; Promises JavaScript promises are used to manage asynchronous requests in your code. It makes life easier and keeps code clean as you
BabelJs – Babel CLI
BabelJS – Babel CLI ”; Previous Next BabelJS comes with a built-in Command Line Interface wherein, the JavaScript code can be easily compiled to the respective ECMA Script using easy to use commands. We will discuss the use of these commands in this chapter. First, we will install babel-cli for our project. We will use babeljs for compiling the code. Create a folder for your project to play around with babel-cli. command npm init Display Package.json created for the above project − Let us run the commands to install babel-cli. Package for babel 6 npm install –save-dev babel-cli Package for babel 7 npm install –save-dev @babel/cli Display We have installed babel-cli and here is the updated package.json − In addition to this, we need to install babel-preset and babel-core. Let us now see the command for the installation. Packages for babel 6 npm install –save-dev babel-preset-env npm install –save-dev babel-core Packages for babel 7 npm install –save-dev @babel/core npm install –save-dev @babel/preset-env Here is the updated package.json for the above commands − Since we need to compile to JavaScript code that we are going to write to have backward compatibility, we will compile it to ECMA Script 5. For this, we need to instruct babel to look for the preset, i.e., es version wherein compilation will be done. We need to create a .babelrc> file in the root folder of our project created as shown below. It contains a json object with the following presets details − { “presets”: [“env”] } For babel 7 the .babelrc is as follows − { “presets”:[“@babel/env”] } We have installed babel local to the project. In order to make use of babel in our project, we need to specify the same in package.json as follows − Compile JS files Now we are ready to compile our JavaScript files. Create a folder src in your project; in this folder, create a file called main.js and write a es6 javascript code as shown below − command npx babel src/main.js Output In the above case, the code from main.js is displayed in the terminal in es5 version. The arrow function from es6 is converted to es5 as shown above. Instead of displaying the compiled code in the terminal, we will store it in a different file as shown below. We have created a folder in our project called out wherein, we want the compiled files to be stored. Following is the command which will compile and store the output where we want it. command npx babel src/main.js –out-file out/main_out.js Output The option in the command –out-file helps us store the output in the file location of our choice. Incase we want the file to be updated every time we make changes to the main file add –watch or -w option to the command as shown below. command npx babel src/main.js –watch –out-file out/main_out.js Output You can make the change to the main file; this change will reflect in the compiled file. In the above case, we changed the log message and the –watch option keeps checking for any change and the same changes are added in the compiled file. Compiled file In our previous sections, we learnt how to compile individual files. Now, we will compile a directory and store the compiled files in another directory. In the src folder, we will create one more js file called main1.js. At present, the src folder has 2 javascript files main.js and main1.js. Following is the code in the files − main.js var arrowfunction = () => { console.log(“Added changes to the log message”); } main1.js var handler = () => { console.log(“Added one more file”); } Following command will compile code from the src folder and store it in the out/ folder. We have removed all the files from the out/ folder and kept it empty. We will run the command and check the output in the out/ folder. command npx babel src –out-dir out We got 2 files in the out folder – main.js and main1.js main.js “use strict”; var arrowfunction = function arrowfunction() { console.log(“Added changes to the log message”); }; main1.js “use strict”; var handler = function handler() { console.log(“Added one more file”); }; Next, we will execute the command given below to compile both files into a single file using babeljs. command npx babel src –out-file out/all.js Output “use strict”; var arrowfunction = function arrowfunction() { console.log(“Added changes to the log message”); }; “use strict”; var handler = function handler() { console.log(“Added one more file”); }; In case we want to ignore some files from being compiled, we can use the option –ignore as shown below. command npx babel src –out-file out/all.js –ignore src/main1.js Output all.js “use strict”; var arrowfunction = function arrowfunction() { console.log(“Added changes to the log message”); }; We can make use of plugins options to be used during file compilation. To make use of plugins, we need to install it as shown below. command npm install –save-dev babel-plugin-transform-exponentiation-operator expo.js let sqr = 9 ** 2; console.log(sqr); command npx babel expo.js –out-file expo_compiled.js –plugins=babel-plugin-transform-exponentiation-operator Output “use strict”; var sqr = Math.pow(9, 2); console.log(sqr); We can also use presets in the command as shown below. command npx babel src/main.js –out-file main_es5.js –presets=es2015 To test the above case, we have removed presets option from .babelrc. main.js var arrowfunction = () => { console.log(“Added changes to the log message”); } main_es5.js “use strict”; var arrowfunction = function arrowfunction() { console.log(“Added changes to the log message”); }; We can also ignore .babelrc from the command line as follows − npx babel –no-babelrc src/main.js –out-file main_es5.js –presets=es2015 To test the above case, we have added presets back to .babelrc and the same will get ignored because of –no-babelrc that we have added in the command. The main_es5.js file details are as follows − main_es5.js “use strict”; var arrowfunction = function arrowfunction() { console.log(“Added changes to the log message”); }; Print Page Previous
BabelJs – Babel Plugins
BabelJS – Babel Plugins ”; Previous Next BabelJS is a javascript compiler that changes the syntax of the code given based on presets and plugins available. The flow of babel compilation involves the following 3 parts − parsing transforming printing The code given to babel is given back as it is with just the syntax changed. We have already seen presets being added to .babelrc file to compile code from es6 to es5 or vice-versa. Presets are nothing but a set of plugins. Babel will not change anything if presets or plugins details are not given during compilation. Let us now discuss the following plugins − transform-class-properties Transform-exponentiation-operator For-of object rest and spread async/await Now, we will create a project setup and work on few plugins, which will give clear understanding of the requirements of plugins in babel. command npm init We have to install the required packages for babel – babel cli, babel core, babel-preset, etc. Packages for babel 6 npm install babel-cli babel-core babel-preset-es2015 –save-dev Packages for babel 7 npm install @babel/cli @babel/core @babel/preset-env –save-dev Create a js file in your project and write your js code. Classes – Transform-class-properties Observe the codes given below for this purpose − Example main.js class Person { constructor(fname, lname, age, address) { this.fname = fname; this.lname = lname; this.age = age; this.address = address; } get fullname() { return this.fname + “-” + this.lname; } } var a = new Person(“Siya”, “Kapoor”, “15”, “Mumbai”); var persondet = a.fullname; Right now, we have not given any preset or plugin details to babel. If we happen to transpile the code using command − npx babel main.js –out-file main_out.js main_out.js class Person { constructor(fname, lname, age, address) { this.fname = fname; this.lname = lname; this.age = age; this.address = address; } get fullname() { return this.fname + “-” + this.lname; } } var a = new Person(“Siya”, “Kapoor”, “15”, “Mumbai”); var persondet = a.fullname; We will get the code as it is. Let us now add preset to .babelrc file. Note − Create .babelrc file inside the root folder of your project. .babelrc for babel 6 .babelrc for babel 7 { “presets”:[“@babel/env”] } We have already installed the presets; now let us run the command again − npx babel main.js –out-file main_out.js main_out.js “use strict”; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (“value” in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(“Cannot call a class as a function”); } } var Person = function () { function Person(fname, lname, age, address) { _classCallCheck(this, Person); this.fname = fname; this.lname = lname; this.age = age; this.address = address; } _createClass(Person, [{ key: “fullname”, get: function get() { return this.fname + “-” + this.lname; } }]); return Person; }(); var a = new Person(“Siya”, “Kapoor”, “15”, “Mumbai”); var persondet = a.fullname; In ES6, class syntax is as follows class Person { constructor(fname, lname, age, address) { this.fname = fname; this.lname = lname; this.age = age; this.address = address; } get fullname() { return this.fname + “-” + this.lname; } } There is constructor and all the properties of the class are defined inside it. Incase, we need to define class properties outside the class we cannot do so. Example class Person { name = “Siya Kapoor”; fullname = () => { return this.name; } } var a = new Person(); var persondet = a.fullname(); console.log(“%c”+persondet, “font-size:25px;color:red;”); If we happen to compile the above code, it will throw an error in babel. This results in the code not getting compiled. To make this work the way we want, we can make use of babel plugin called babel-plugin-transform-class-properties. To make it work, we need to install it first as follows − Packages for babel 6 npm install –save-dev babel-plugin-transform-class-properties Package for babel 7 npm install –save-dev @babel/plugin-proposal-class-properties Add the plugin to .babelrc file for babel 6 − .babelrc for babel 7 { “plugins”: [“@babel/plugin-proposal-class-properties”] } Now, we will run the command again. command npx babel main.js –out-file main_out.js main.js class Person { name = “Siya Kapoor”; fullname = () => { return this.name; } } var a = new Person(); var persondet = a.fullname(); console.log(“%c”+persondet, “font-size:25px;color:red;”); Compiled to main_out.js class Person { constructor() { this.name = “Siya Kapoor”; this.fullname = () => { return this.name; }; } } var a = new Person(); var persondet = a.fullname(); console.log(“%c”+persondet, “font-size:25px;color:red;”); Output Following is the output we get when used in a browser − Exponentiation Operator – transform-exponentiation-operator ** is the operator used for exponentiation in ES7. Following example shows the working of same in ES7. It also shows how to transpile code using babeljs. Example let sqr = 9 ** 2; console.log(“%c”+sqr, “font-size:25px;color:red;”); To transpile the exponentiation operator, we need a plugin to be installed as follows − Packages for babel 6 npm install –save-dev babel-plugin-transform-exponentiation-operator Packages for babel 7 npm install –save-dev @babel/plugin-transform-exponentiation-operator Add the plugin details to .babelrc file as follows for babel 6 − { “plugins”: [“transform-exponentiation-operator”] } .babelrc for babel 7 { “plugins”: [“@babel/plugin-transform-exponentiation-operator”] } command npx babel exponeniation.js –out-file exponeniation_out.js exponeniation_out.js let sqr = Math.pow(9, 2); console.log(“%c” + sqr, “font-size:25px;color:red;”); Output For-of The packages required for the plugins in babel6 and 7 are as follows − Babel6 npm install –save-dev babel-plugin-transform-es2015-for-of Babel 7 npm install –save-dev @babel/plugin-transform-for-of .babelrc for babel6 { “plugins”: [“transform-es2015-for-of”] } .babelrc for babel7 { “plugins”: [“@babel/plugin-transform-for-of”] } forof.js let foo = [“PHP”, “C++”, “Mysql”, “JAVA”]; for (var i of foo) { console.log(i); } command npx babel forof.js –out-file forof_es5.js Forof_es5.js let foo = [“PHP”, “C++”, “Mysql”, “JAVA”]; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = foo[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step
BabelJs – Babel Presets
BabelJS – Babel Presets ”; Previous Next Babel presets are config details to the babel-transpiler telling it to transpile it in the specified mode. Here are some of the most popular presets we are going to discuss in this chapter − ES2015 Env React We need to use presets that have the environment in which we want the code to be converted. For example, es2015 preset will convert the code to es5. Preset with value env will also convert to es5. It also has additional feature, i.e., options. In case you want the feature to be supported on recent versions of browsers, babel will convert the code only if there is no support of features on those browsers. With Preset react, Babel will transpile the code when to react. To work with Presets, we need to create .babelrc file in our project root folder. To show the working, we will create a project setup as shown below. command npm init We have to install the required babel preset as follows along with babel cli, babel core, etc. Babel 6 packages npm install babel-cli babel-core babel-preset-es2015 –save-dev Babel 7 Packages npm install @babel/cli @babel/core @babel/preset-env –save-dev Note − babel-preset-es2015 is deprecated babel 7 onwards. es2015 or @babel/env Create .babelrc file in the root of the project (babel 6) − In .babelrc, the presets is es2015. This is the indication to the babel compiler that we want the code to be converted to es2015. For babel 7, we need to use presets as follows − { “presets”:[“@babel/env”] } Here is the package.json after installation − Since we have installed babel locally, we have added babel command in the scripts section in package.json. Let us work on a simple example to check for the transpiling using preset es2015. Example main.js let arrow = () => { return “this is es6 arrow function”; } Transpiled to es5 as shown below. command npx babel main.js –out-file main_es5.js main_es5.js “use strict”; var arrow = function arrow() { return “this is es6 arrow function”; }; Env Using Env preset, you can specify the environment you the final code to be transpiled to. We are going to use the same project setup created above and change the presets from es2015 to env as shown below. In addition, we need to install the babel-preset-env. We will execute the command given below to install the same. command npm install babel-preset-env –save-dev We will compile main.js again and see the output. main.js let arrow = () => { return “this is es6 arrow function”; } command npx babel main.js –out-file main_env.js main_env.js “use strict”; var arrow = function arrow() { return “this is es6 arrow function”; }; We have seen the transpiled code is es5. Incase we know the environment in which our code is going to execute, we can use this preset to specify it. For example, if we specify the browsers as last 1 version for chrome and firefox as shown below. command npx babel main.js –out-file main_env.js main_env.js “use strict”; let arrow = () => { return “this is es6 arrow function”; }; We are now getting the arrow function syntax as it is. It is not transpiled into ES5 syntax. This is because the environment which we want our code to support, already has support for the arrow function. Babel takes care of compiling the code based on environment using the babel-preset-env. We can also target the compilation based on the nodejs environment as shown below The final compilation of the code is as shown below. command npx babel main.js –out-file main_env.js main_env.js “use strict”; let arrow = () => { return “this is es6 arrow function”; }; Babel compiles the code as per the current version of nodejs. React Preset We can use react preset when we are using Reactjs. We will work on a simple example and use react preset to see the output. To use the preset, we need to install babel-preset-react (babel 6) as follows − npm install –save-dev babel-preset-react For babel 7, it is as follows − npm install –save-dev @babel/preset-react Changes to .babelrc are as follows for babel6 − For babel 7 { “presets”: [“@babel/preset-react”] } main.js <h1>Hello, world!</h1> command npx babel main.js –out-file main_env.js main_env.js React.createElement( “h1”, null, “Hello, world!” ); The code from main.js is converted to reactjs syntax with preset:react. Print Page Previous Next Advertisements ”;
BabelJS – Project setup using Babel 6 ”; Previous Next In this chapter, we will see how to use babeljs inside our project. We will create a project using nodejs and use http local server to test our project. Create Project Setup In this section, we will learn how to create project setup. Create a new directory and run the following command to create the project − npm init Output Upon execution, the above command generates the following output − Following is the package.json that is created − We will install the packages required to start working with babeljs. We will execute the following command to install babel-cli, babel-core, babel-preset-es2015. npm install babel-cli babel-core babel-preset-es2015 –save-dev Output Upon execution, the above command generates the following output − Package.json is updated as follows − We need http server to test the js file. Execute the following command to install http server − npm install lite-server –save-dev We have added the following details in package.json − In scripts, Babel takes care of transpiling the scripts.js from src folder and saves it in dev folder with name scripts.bundle.js. We have added the full command to compile the code we want in package.json. In addition, build is added which will start the lite-server to test the changes. The src/scripts.js has the JavaScript as follows − class Student { constructor(fname, lname, age, address) { this.fname = fname; this.lname = lname; this.age = age; this.address = address; } get fullname() { return this.fname +”-“+this.lname; } } We have called the transpiled script in index.html as follows − <html> lt;head></head> <body> <script type=”text/javascript” src=”dev/scripts.bundle.js?a=11″></script> <h1 id=”displayname”></h1> <script type=”text/javascript”> var a = new Student(“Siya”, “Kapoor”, “15”, “Mumbai”); var studentdet = a.fullname; document.getElementById(“displayname”).innerHTML = studentdet; </script> </body> </html> We need to run the following command, which will call babel and compile the code. The command will call Babel from package.json − npm run babel The scripts.bundle.js is the new js file created in dev folder − The output of dev/scripts.bundle.js is as follows − “use strict”; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (“value” in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(“Cannot call a class as a function”); } } var Student = function () { function Student(fname, lname, age, address) { _classCallCheck(this, Student); this.fname = fname; this.lname = lname; this.age = age; this.address = address; } _createClass(Student, [{ key: “fullname”, get: function get() { return this.fname + “-” + this.lname; } }]); return Student; }(); Now let us run the following command to start the server − npm run build When the command runs, it will open the url in the browser − Output The above command generates the following output − Print Page Previous Next Advertisements ”;