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.
<script> 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 </script>
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.
YOU SHOULDNT DO THAT.
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.https://developer.wordpress.org/block-editor/contributors/develop/scripts/#polyfill-scripts
It also says:
provides a webpack plugin to help extract WordPress dependencies from bundles.
the plugin by default.https://developer.wordpress.org/block-editor/contributors/develop/scripts/#bundling-and-code-sharing
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.
Comments are closed.