BabelJS - Babel Polyfill


Advertisements

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 −

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

.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 −

Babel Command

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 −

Node Modules

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

Babel Polyfill Testing

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>

String Padding Output

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

WeakMap 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

Array Methods Js
Advertisements