What is babel-polyfill and why it is important?

 

babel-polyfill will emulate a full ES6 environment. For example, without the polyfill, the following code:

function allAdd() {
    return Array.from(arguments).map((a) => a + 2);
}

will be transpiled to:

function allAdd() {
    return Array.from(argument).map(function (a) {
        return a + 2;
    });
}

This code will not work everywhere, because Array.from in not supported by every browser:

Uncaught TypeError: Array.from is not a function

To solve this problem we need to use a polyfill. A polyfill is a piece of code, that replicate the native API that does not exist in the current runtime.

To include the Babel polyfill, we need to install it:

npm install babel-polyfill --save-dev

 

Use the babel-polyfill in your source code

To include the polyfill you need to require it at the top of the entry point to your application. in order to use babel-polyfill withj your applciation, you can use one of following three methods.

 

method 01

With require

require("babel-polyfill");

 

method 02

If you are using ES6’s import syntax in your application’s entry point, you should instead import the polyfill at the top of the entry point to ensure the polyfills are loaded first.

With ES6 import.

import "babel-polyfill";

 

method 03

With webpack.config.js, add babel-polyfill to your entry array:

module.exports = {
  entry: ["babel-polyfill", "./app/js"]
};

One thought on “What is babel-polyfill and why it is important?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s