Wordpress Code

A tale about polyfills

What is babel polyfill?

babel-polyfill is a lib that you can import into your code. By doing so it will emulate a full ES6 environment.

The following code will not run in any browser without the necessary fixes that babel-polyfill provides.

    var nodes = document.querySelectorAll('.my-wanted-elements');
    // here we have a NodeList, but we want an Array of elements.
    var els = Array.from(nodes);
    // els is an array

Ok, so can I use it in every script in my plugins?

NO, you shouldnt use it in that way.

In wordpress there is a polyfill provided by the wp-polyfill.

It is bad practice to include the babel-polyfill several times.

Let’s imagine the following scenario

We have Plugin A and Plugin B, both enqueue a JS file via wp_enqueue_script().

If we use Gulp or Webpack to build our assets we may be tented to inject the babel-polyfill in both scripts.


Ok, so what is the proposed solution?

WordPress official documentation states the following:

It is recommended to use the main wp-polyfill script handle which takes care of loading all the below mentioned polyfills.

It also says:

When using a JavaScript bundler like webpack, the scripts mentioned here can be excluded from the bundle and provided by WordPress in the form of script dependencies.



provides a webpack plugin to help extract WordPress dependencies from bundles. @wordpress/scripts

build script includes

the plugin by default.

So you can use a webpack setup and add the plugin mentioned above and it will remove the dependencies from wordpress.

This way you let WP inject the polyfills independently from your scripts. You will still need to add wp-polyfill as dependency.

Another solution can be to write in ES6 and use wp-polifyll as dependencies.