Transpile ES8 features to ES5

BabelJS – Transpile ES8 features to ES5 ”; Previous Next String padding is the new ES8 feature added to javascript. We will work on simple example, which will transpile string padding to ES5 using babel. String Padding String padding adds another string from the left side as per the length specified. The syntax for string padding is as shown below − Syntax str.padStart(length, string); str.padEnd(length, string); Example const str = ”abc”; console.log(str.padStart(8, ”_”)); console.log(str.padEnd(8, ”_”)); Output _____abc abc_____ ES8 – String Padding const str = ”abc”; console.log(str.padStart(8, ”_”)); console.log(str.padEnd(8, ”_”)); command npx babel strpad.js –out-file strpad_es5.js Babel – ES5 ”use strict”; var str = ”abc”; console.log(str.padStart(8, ”_”)); console.log(str.padEnd(8, ”_”)); The js has to be used along with babel-polyfill as shown below − test.html <!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=”strpad_es5.js”></script> </body> </html> Print Page Previous Next Advertisements ”;

Working with Babel and Webpack

BabelJS – Working with Babel and Webpack ”; Previous Next Webpack is a module bundler which packs all modules with dependencies – js, styles, images, etc. into static assets .js, .css, .jpg , .png, etc. Webpack comes with presets which help for compilation into the required form. For example, react preset that helps to get the final output in react form, es2015 or env preset that helps to compile the code in ES5 or 6 or 7, etc. We have used babel 6 in the project setup. In case you want to switch to babel7, install the required packages of babel using @babel/babel-package-name. Here, we will discuss project setup using babel and webpack. Create a folder called and open the same in visual studio IDE. To create the project setup, run npm initbabelwebpack as follows − Here is the package.json created after npm init − Now, we will install the necessary packages we need to work with babel and webpack. npm install –save-dev webpack npm install –save-dev webpack-dev-server npm install –save-dev babel-core npm install –save-dev babel-loader npm install –save-dev babel-preset-env Here is the Package.json after installation − Now, we will create a webpack.config.js file, which will have all the details to bundle the js files. These files will be compiled it into es5 using babel. To run webpack using server, we use webpack-server. Following are the details added to it − We have added the publish command which will start the webpack-dev-server and will update the path where the final files are stored. Right now the path that we are going to use to update the final files is the /dev folder. To use webpack, we need to run the following command − npm run publish First we need to create the webpack.config.js files. These will have the configuration details for webpack to work. The details in the file are as follows − var path = require(”path”); module.exports = { entry: { app: ”./src/main.js” }, output: { path: path.resolve(__dirname, ”dev”), filename: ”main_bundle.js” }, mode:”development”, module: { rules: [ { test: /.js$/, include: path.resolve(__dirname, ”src”), loader: ”babel-loader”, query: { presets: [”env”] } } ] } }; The structure of the file is as shown above. It starts with theh path, which gives the current path details. var path = require(”path”); //gives the current path Next is the module.exports object, which has properties entry, output and module. The entry is the start point. Here, we need to give the main js files that has to be compiled. entry: { app: ”./src/main.js” }, path.resolve(_dirname, ‘src/main.js’) — will look for the src folder in the directory and main.js in that folder. Output output: { path: path.resolve(__dirname, ”dev”), filename: ”main_bundle.js” }, Output is an object with path and filename details. Path will hold the folder in which the compiled file will be kept and filename will tell the name of final file to be used in your .html file. module module: { rules: [ { test: /.js$/, include: path.resolve(__dirname, ”src”), loader: ”babel-loader”, query: { presets: [”env”] } } ] } Module is an object with details of the rules. It has the following properties − test include loader query Test will hold details of all the js files ending with .js. It has the pattern, which will look for .js at the end in the entry point given. Include instructs the folder in use on the files to be looked at. Loader uses babel-loader for compiling codes. Query has property presets, which is an array with value env – es5 or es6 or es7. Create folder src and main.js in it; write your js code in ES6. Later, run the command to see it getting compiled to es5 using webpack and babel. src/main.js let add = (a,b) => { return a+b; }; let c = add(10, 20); console.log(c); Run the command − npm run pack The compiled file looks as follows − dev/main_bundle.js !function(e) { var t = {}; function r(n) { if(t[n])return t[n].exports;var o = t[n] = {i:n,l:!1,exports:{}}; return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports } r.m = e,r.c = t,r.d = function(e,t,n) { r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n}) }, r.r = function(e) { “undefined”!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:”Module”}),Object.defineProperty(e,”__esModule”,{value:!0}) }, r.t = function(e,t) { if(1&t&&(e = r(e)),8&t)return e; if(4&t&&”object”==typeof e&&e&&e.__esModule)return e; var n = Object.create(null); if(r.r(n),Object.defineProperty(n,”default”,{enumerable:!0,value:e}),2&t&&”string”!=typeof e)for(var o in e)r.d(n,o,function(t) {return e[t]}.bind(null,o)); return n }, r.n = function(e) { var t = e&&e.__esModule?function() {return e.default}:function() {return e}; return r.d(t,”a”,t),t }, r.o = function(e,t) {return Object.prototype.hasOwnProperty.call(e,t)}, r.p = “”,r(r.s = 0) }([function(e,t,r) {“use strict”;var n = function(e,t) {return e+t}(10,20);console.log(n)}]); !function(e) { var t = {}; function r(n) { if(t[n])return t[n].exports; var o = t[n] = {i:n,l:!1,exports:{}}; return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports } r.m = e,r.c = t,r.d = function(e,t,n) { r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n}) }, r.r = function(e) { “undefined”!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:”Module”}),Object.defineProperty(e,”__esModule”,{value:!0}) }, r.t = function(e,t) { if(1&t&&(e=r(e)), 8&t)return e; if(4&t&&”object”==typeof e&&e&&e.__esModule)return e; var n = Object.create(null); if( r.r(n), Object.defineProperty(n,”default”,{enumerable:!0,value:e}), 2&t&&”string”!=typeof e ) for(var o in e)r.d(n,o,function(t) {return e[t]}.bind(null,o)); return n }, r.n = function(e) { var t = e&&e.__esModule?function() {return e.default}:function() {return e}; return r.d(t,”a”,t),t }, r.o = function(e,t) { return Object.prototype.hasOwnProperty.call(e,t) }, r.p = “”,r(r.s = 0) }([function(e,t,r) { “use strict”; var n = function(e,t) {return e+t}(10,20); console.log(n) }]); The code is compiled as shown above. Webpack adds some code which is required internally and the code from main.js is seen at the end. We have consoled the value as shown above. Add the final js file in .html file as follows − <html> <head></head> <body> <script type=”text/javascript” src=”dev/main_bundle.js”></script> </body> </html> Run the command − npm run publish To check the output, we can open the file in − http://localhost:8080/ We get the console value as shown above. Now let us try to compile to a single file using webpack and babel. We will use webpack to bundle multiple js files into a single file. Babel will be used to compile the es6 code to es5. Now, we have 2 js files in the src/ folder – main.js and Person.js as follows − person.js export class Person { constructor(fname, lname, age, address) { this.fname = fname; this.lname =

BabelJs – Discussion

Discuss BabelJS ”; Previous Next 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. Print Page Previous Next Advertisements ”;

BabelJs – Useful Resources

BabelJS – Useful Resources ”; Previous Next The following resources contain additional information on BabelJS. Please use them to get more in-depth knowledge on this. Python Programming Certification 2024 Most Popular  9 Courses     1 eBooks Tutorialspoint More Detail Artificial Intelligence and Machine Learning Certification 2024 Most Popular  7 Courses     1 eBooks Tutorialspoint More Detail Java Certification 2024 Best Seller  7 Courses     1 eBooks Tutorialspoint More Detail Print Page Previous Next Advertisements ”;

BabelJs – Project Setup Using Babel 7

BabelJS – Project setup using Babel 7 ”; Previous Next The latest version of Babel, 7 released with changes to the already existing packages. The installation part remains the same as it was for Babel 6. The only difference in Babel 7 is that all the packages need to be installed with @babel/, for example @babel/core, @babel/preset-env, @babel/cli, @babel/polyfill, etc. Here is a project setup created using babel 7. Command Execute the following command to start the project setup − npm init Install following packages npm install –save-dev @babel/core npm install –save-dev @babel/cli npm install –save-dev @babel/preset-env Here is the package.json created − Now will create a .babelrc file in the root folder − Create a folder src/ and add file main.js to it and write your code to transpile to es5. src/main.js let add = (a,b) => { return a+b; } command to transpile npx babel src/main.js –out-file main_es5.js main_es5.js “use strict”; var add = function add(a, b) { return a + b; }; The working of Babel 7 remains the same as Babel 6. The only difference is the pacakge installation with @babel. There are some presets deprecated in babel 7. The list is as follows − ES20xx presets babel-preset-env babel-preset-latest Stage presets in Babel Also the year from the packages is removed – @babel/plugin-transform-es2015-classes is now @babel/plugin-transform-classes We will see one more example of working with typescript and transpile it to Es2015 JavaScript using typescript preset and babel 7. To work with typescript, we need typescript package to be installed as follows − npm install –save-dev @babel/preset-typescript Create test.ts file in the src/ folder and write the code in typescript form − test.ts let getName = (person: string) => { return “Hello, ” + person; } getName(“Siya”); .babelrc command npx babel src/test.ts –out-file test.js test.js “use strict”; var getName = function getName(person) { return “Hello, ” + person; }; getName(“Siya”); Print Page Previous Next Advertisements ”;

BabelJs – Overview

BabelJS – Overview ”; Previous Next 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 projects. Disadvantages of

BabelJs – Babel Polyfill

BabelJS – Babel Polyfill ”; Previous Next Babel Polyfill adds support to the web browsers for features, which are not available. Babel compiles the code from recent ecma version to the one, which we want. It changes the syntax as per the preset, but cannot do anything for the objects or methods used. We have to use polyfill for those features for backward compatibility. Features that can be polyfilled Following is the list of features that need polyfill support when used in older browsers − Promises Map Set Symbol Weakmap Weakset Array.from, Array.includes, Array.of, Array#find, Array.buffer, Array#findIndex Object.assign, Object.entries, Object.values We will create project setup and also see the working of babel polyfill. command npm init We will now install the packages required for babel. 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 Here is the final package.json − We will also add es2015 to the presets, as we want to compile the code to es5. .babelrc for babel 6 .babelrc for babel 7 { “presets”:[“@babel/env”] } We will install a lite-serve so that we can test our code in browser − npm install –save-dev lite-server Let us add babel command to compile our code in package.json − We have also added the build command which calls the lite-server. Babel-polyfill gets installed along with the babel-core package. The babel-polyfill will be available in node modules as shown below − We will further work on promises and use babel-polyfill along with it. ES6 – Promises let timingpromise = new Promise((resolve, reject) => { setTimeout(function() { resolve(“Promise is resolved!”); }, 1000); }); timingpromise.then((msg) => { console.log(“%c”+msg, “font-size:25px;color:red;”); }); command npx babel promise.js –out-file promise_es5.js BabelJS – ES5 “use strict”; var timingpromise = new Promise(function (resolve, reject) { setTimeout(function () { resolve(“Promise is resolved!”); }, 1000); }); timingpromise.then(function (msg) { console.log(“%c”+msg, “font-size:25px;color:red;”); }); The compilation need not change anything. The code for promise has been transpiled as it is. But browsers which do not support promises will throw an error even though we have compiled the code to es5. To solve this issue, we need to add polyfill along with the final es5 compiled code. To run the code in browser, we will take the babel-polyfill file from node modules and add it to the .html file where we want to use promises as shown below − index.html <html> <head> </head> <body> <h1>Babel Polyfill Testing</h1> <script type=”text/javascript” src=”node_modules/babel-polyfill/dist/polyfill.min.js”></script> <script type=”text/javascript” src=”promise_es5.js”></script> </body> </html> output In index.html file, we have used the polyfill.min.js file from node_modules followed by promise_es5.js − <script type=”text/javascript” src=”node_modules/babel-polyfill/dist/polyfill.min.js”></script> <script type=”text/javascript” src=”promise_es5.js”></script> Note − Polyfill file has to be used at the start before the main javascript call. String Padding String padding adds another string from the left side as per the length specified. The syntax for string padding is as shown below − Syntax str.padStart(length, string); str.padEnd(length, string); Example const str = ”abc”; console.log(str.padStart(8, ”_”)); console.log(str.padEnd(8, ”_”)); Output _____abc abc_____ Babel – ES5 npx babel strpad.js –out-file strpad_es5.js command ”use strict”; var str = ”abc”; console.log(str.padStart(8, ”_”)); console.log(str.padEnd(8, ”_”)); The js has to be used along with babel-polyfill as shown below − test.html <!DOCTYPE html> <html> <head> <title>BabelJs Testing </title> </head> <body> <script src=”node_modules/babel-polyfill/dist/polyfill.min.js” type=”text/javascript”></script> <script type=”text/javascript” src=”strpad_es5.js”></script> </body> </html> Map, Set, WeakSet, WeakMap In this section, we will learn aboutMap, Set, WeakSet, WeakMap. Map is a object with key / value pair. Set is also a object but with unique values. WeakMap and WeakSet iare also objects with key/value pairs. Map, Set, WeakMap and WeakSet are new features added to ES6. To transpile it to be used in older browsers, we need to make use of polyfill. We will work on an example and use polyfill to compile the code. Example let m = new Map(); //map example m.set(“0″,”A”); m.set(“1″,”B”); console.log(m); let set = new Set(); //set example set.add(”A”); set.add(”B”); set.add(”A”); set.add(”B”); console.log(set); let ws = new WeakSet(); //weakset example let x = {}; let y = {}; ws.add(x); console.log(ws.has(x)); console.log(ws.has(y)); let wm = new WeakMap(); //weakmap example let a = {}; wm.set(a, “hello”); console.log(wm.get(a)); Output Map(2) {“0” => “A”, “1” => “B”} Set(2) {“A”, “B”} true false hello command npx babel set.js –out-file set_es5.js Babel-ES5 “use strict”; var m = new Map(); //map example m.set(“0”, “A”); m.set(“1”, “B”); console.log(m); var set = new Set(); //set example set.add(”A”); set.add(”B”); set.add(”A”); set.add(”B”); console.log(set); var ws = new WeakSet(); //weakset example var x = {}; var y = {}; ws.add(x); console.log(ws.has(x)); console.log(ws.has(y)); var wm = new WeakMap(); //weakmap example var a = {}; wm.set(a, “hello”); console.log(wm.get(a)); The js has to be used along with babel-polyfill as shown below − test.html <!DOCTYPE html> <html> <head> <title>BabelJs Testing</title> </head> <body> <script src=”node_modules/babel-polyfill/dist/polyfill.min.js” type=”text/javascript”></script> <script type=”text/javascript” src=”set_es5.js”></script> </body> </html> Output Array Methods Many properties and methods can be used on array; for example, array.from, array.includes, etc. Let us consider working on the following example to understand this better. Example arraymethods.js var arrNum = [1, 2, 3]; console.log(arrNum.includes(2)); console.log(Array.from([3, 4, 5], x => x + x)); Output true [6, 8, 10] command npx babel arraymethods.js –out-file arraymethods_es5.js Babel-es5 “use strict”; var arrNum = [1, 2, 3]; console.log(arrNum.includes(2)); console.log(Array.from([3, 4, 5], function (x) { return x + x; })); The methods used on the array are printed as they are. To make them work on older browsers, we need to add polyfill file at the start as shown below − index.html <html> <head></head> <body> <h1>Babel Polyfill Testing</h1> <script type=”text/javascript” src=”node_modules/babel-polyfill/dist/polyfill.min.js”></script> <script type=”text/javascript” src=”arraymethods_es5.js”></script> </body> </html> Output Print Page Previous Next Advertisements ”;

Transpile ES6 Modules to ES5

BabelJS – Transpile ES6 Modules to ES5 ”; Previous Next In this chapter, we will see how to transpile ES6 modules to ES5 using Babel. Modules Consider a scenario where parts of JavaScript code need to be reused. ES6 comes to your rescue with the concept of Modules. A module is nothing more than a chunk of JavaScript code written in a file. The functions or variables in a module are not available for use, unless the module file exports them. In simpler terms, the modules help you to write the code in your module and expose only those parts of the code that should be accessed by other parts of your code. Let us consider an example to understand how to use module and how to export it to make use of it in the code. Example add.js var add = (x,y) => { return x+y; } module.exports=add; multiply.js var multiply = (x,y) => { return x*y; }; module.exports = multiply; main.js import add from ”./add”; import multiply from ”./multiply” let a = add(10,20); let b = multiply(40,10); console.log(“%c”+a,”font-size:30px;color:green;”); console.log(“%c”+b,”font-size:30px;color:green;”); I have three files add.js that adds 2 given numbers, multiply.js that multiplies two given numbers and main.js, which calls add and multiply, and consoles the output. To give add.js and multiply.js in main.js, we have to export it first as shown below − module.exports = add; module.exports = multiply; To use them in main.js, we need to import them as shown below import add from ”./add”; import multiply from ”./multiply” We need module bundler to build the files, so that we can execute them in the browser. We can do that − Using Webpack Using Gulp ES6 modules and Webpack In this section, we will see what the ES6 modules are. We will also learn how to use webpack. Before we start, we need to install the following packages − npm install –save-dev webpack npm install –save-dev webpack-dev-server npm install –save-dev babel-core npm install –save-dev babel-loader npm install –save-dev babel-preset-env Package.json We have added pack and publish tasks to scripts to run them using npm. Here is the webpack.config.js file which will build the final file. webpack.config.js var path = require(”path”); module.exports = { entry: { app: ”./src/main.js” }, output: { path: path.resolve(__dirname, ”dev”), filename: ”main_bundle.js” }, mode:”development”, module: { rules: [ { test: /.js$/, include: path.resolve(__dirname, ”src”), loader: ”babel-loader”, query: { presets: [”env”] } } ] } }; Run the command npm run pack to build the files. The final file will be stored in the dev/ folder. command npm run pack dev/main_bundle.js common file is created. This file combines add.js, multiply.js and main.js and stores it in dev/main_bundle.js. /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== ”undefined” && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: ”Module” }); /******/ } /******/ Object.defineProperty(exports, ”__esModule”, { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === ”object” && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, ”default”, { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != ”string”) for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module[”default”]; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, ”a”, getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = “”; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = “./src/main.js”); /******/ }) /************************************************************************/ /******/ ({ /***/ “./src/add.js”: /*!********************!* !*** ./src/add.js ***! ********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { “use strict”; eval( “nnvar add = function add(x, y) {n return x + y;n}; nnmodule.exports = add; nn//# sourceURL = webpack:///./src/add.js?” ); /***/ }), /***/ “./src/main.js”: /*!*********************!* !*** ./src/main.js ***! *********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { “use strict”; eval( “nnvar _add = __webpack_require__(/*! ./add */ “./src/add.js”); nnvar _add2 = _interopRequireDefault(_add); nnvar _multiply = __webpack_require__(/*! ./multiply */ “./src/multiply.js”); nnvar _multiply2 = _interopRequireDefault(_multiply); nnfunction _interopRequireDefault(obj) { return obj &gt;&gt; obj.__esModule ? obj : { default: obj }; } nnvar a = (0, _add2.default)(10, 20); nvar b = (0, _multiply2.default)(40, 10); nnconsole.log(“%c” + a, “font-size:30px;color:green;”); nconsole.log(“%c” + b, “font-size:30px;color:green;”); nn//# sourceURL = webpack:///./src/main.js?” ); /***/ }), /***/ “./src/multiply.js”: /*!*************************!* !*** ./src/multiply.js

Working with Babel and JSX Working with Babel and Flow Working with BabelJS and Gulp BabelJs – Examples

BabelJS – Working with Babel and JSX ”; Previous Next In this chapter, we will understand working with JSX and babel. Before we get into the details, let us understand what JSX is. What is JSX? JSX is a JavaScript code with a combination of xml syntax in it. JSX tag has tag name, attributes and children which make it look like xml. React uses JSX for templating instead of regular JavaScript. It is not necessary to use it, however, following are some pros that come with it. It is faster because it performs optimization while compiling code to JavaScript. It is also type-safe and most of the errors can be caught during compilation. It makes it easier and faster to write templates, if you are familiar with HTML. We have used babel 6 in the project setup. In case you want to switch to babel 7, install the required packages of babel using @babel/babel-package-name. We will create project setup and use webpack to compile jsx with react to normal JavaScript using Babel. To start the project setup, run the commands given below for babel, react and webpack installation. command npm init Now, we will install the necessary packages we need to work with – babel ,webpack and jsx − npm install –save-dev webpack npm install –save-dev webpack-cli npm install –save-dev webpack-dev-server npm install –save-dev babel-core npm install –save-dev babel-loader npm install –save-dev babel-preset-es2015 npm install –save-dev babel-preset-react npm install –save-dev react npm install –save-dev react-dom Here is the package.json after installation − Now will create a webpack.config.js file, which will have all the details to bundle the js files and compile it into es5 using babel. To run webpack using server, there is something called webpack-server. We have added command called publish; this command will start the webpack-dev-server and will update the path where the final files are stored. Right now the path that we are going to use to update the final files is the /dev folder. To use webpack we need to run the following command − npm run publish We will create the webpack.config.js files, which have the configuration details for webpack to work. The details in the file are as follows − var path = require(”path”); module.exports = { entry: { app: ”./src/main.js” }, output: { path: path.resolve(__dirname, ”dev”), filename: ”main_bundle.js” }, mode:”development”, module: { rules: [ { test:/.(js|jsx)$/, include: path.resolve(__dirname, ”src”), loader: ”babel-loader”, query: { presets: [”es2015”,”react”] } } ] } }; The structure of the file is as shown above. It starts with the path, which gives the current path details. var path = require(”path”); //gives the current path Next is the module.exports object, which has properties entry, output and module. Entry is the start point. Here we need to give the main js files we want to compile. entry: { app: ”./src/main.js” }, path.resolve(_dirname, ‘src/main.js’) — will look for the src folder in the directory and main.js in that folder. Output output: { path: path.resolve(__dirname, ”dev”), filename: ”main_bundle.js” }, Output is an object with path and filename details. Path will hold the folder in which the compiled file will be kept and filename will tell the name of the final file to be used in your .html file. module module: { rules: [ { test:/.(js|jsx)$/, include: path.resolve(__dirname, ”src”), loader: ”babel-loader”, query: { presets: [”es2015”,”react”] } } ] } Module is object with rules details which has properties ie test, include , loader, query. Test will hold details of all the js file ending with .js and .jsx.It has the pattern which will look for .js and .jsx at the end in the entry point given. Include tells the folder to be used for looking the files. Loader uses babel-loader for compiling code. Query has property presets, which is array with value env – es5 or es6 or es7. We have used es2015 and react as the preset. Create folder src/. Add main.js and App.jsx in it. App.jsx import React from ”react”; class App extends React.Component { render() { var style = { color: ”red”, fontSize: 50 }; return ( <div style={style}> Hello World!!! </div> ); } } export default App; main.js import React from ”react”; import ReactDOM from ”react-dom”; import App from ”./App.jsx”; ReactDOM.render(, document.getElementById(”app”)); Run the following command to bundle the .js file and convert it using presets es2015 and react. command npm run pack Add main_bundle.js from the dev folder to index.html − <!DOCTYPE html> <html lang = “en”> <head> <meta charset = “UTF-8”> <title>React App</title> </head> <body> <div id = “app”></div> <script src = “dev/main_bundle.js”></script> </body> </html> command npm run publish Output Print Page Previous Next Advertisements ”;

BabelJs – CLI

BabelJS – CLI ”; Previous Next Babel comes with a built-in command line interface, which can be used to compile the code. Create a directory wherein you would be working. Here, we have created directory called babelproject. Let us make use of nodejs to create the project details. We have used npm init to create the project as shown below − Here is the project structure that we created. Now to work with Babel we need to instal Babel cli, Babel preset, Babel core as shown below − babel-cli Execute the following command to install babel-cli − npm install –save-dev babel-cli babel-preset Execute the following command to install babel-preset − npm install –save-dev babel-preset-env babel-core Execute the following command to install babel-core − npm install –save-dev babel-core After installation, here are the details available in package.json − We have installed babel plugins local to the project. This is done so that we can use babel differently on our projects based on the project requirements and also different versions of babeljs. Package.json gives the version details of babeljs used. In order to make use of babel in our project, we need to specify the same in package.json as follows − Babel is mainly used to compile JavaScript code, which will have backward compatibility. Now, we will write our code in ES6 -> ES5 or ES7 -> ES5 also ES7->ES6, etc. To provide instructions to Babel on the same, while executing, we need to create a file called .babelrc in the root folder. It contains a json object with details of the presets as shown below − We will create the JavaScript file index.js and compile it to es2015 using Babel. Before that, we need to install the es2015 preset as follows − In index.js, we have created a function using the arrow function which is a new feature added in es6. Using Babel, we will compile the code to es5. To execute to es2015, following command is used − npx babel index.js Output It displays the index.js code in es5 as shown above. We can store the output in the file by executing the command as shown below − npx babel index.js –out-file index_es5.js Output Here is the file that we created, index_es5.js − Print Page Previous Next Advertisements ”;