Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to polyfill Array.prototype.find using webpack ProvidePlugin?

I'm using webpack and have followed examples to polyfill fetch and Promise for older browsers based on the whatwg-fetch and and es6-promise packages respectively.

new webpack.ProvidePlugin({
    'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch',
    'Promise': 'exports?global.Promise!es6-promise'
}),

This all makes sense however now I need to polyfill Array.prototype.find() but can no find of how to achieve this using webpack's ProvidePlugin feature. The thing that makes find different is that it is essentially a method on the Array prototype and I haven't found any examples of how to specify such things using ProvidePlugin. Has anybody used webpack to polyfill ES6 array functions like these? Any pointers on how this can be achieved? Am I going about this the wrong/outdated way or is there a better way to achieve what I need?

So far I've tried experimenting around with the syntax using this polyfill package from paulmillr but haven't had success using it with ProvidePlugin.

UPDATES

Doing more research on this lead me to babel polyfill. And these resources:

  • Why does Object.assign() require a polyfill when babel-loader is being used?
  • Babel polyfill? What is that?
  • Getting Babel 6 to work with IE8 (via. Gulp/Webpack)

I've found also here that the window.fetch polyfill is missing from babel-polyfill which explains why it's perhaps often a special case handled by ProvidePlugin. I'm also piecing together that ProvidePlugin is more of a convenience tool than a general tool for applying polyfills. Directly importing babel-polyfill and removing Promise and other ES6 pollyfills except for fetch is showing to be somewhat promising in my experiments so far.

like image 986
jpierson Avatar asked Jan 07 '16 04:01

jpierson


1 Answers

What I've settled on for now is the following solution.

In the root of the application import/require babel-polyfill for general ES6 polyfills such as Array.prototype.find, Object.assign, and Promise. Since fetch is a special case, because it is viewed as not suitable for all environments, a separate polyfill is included for whatwg-fetch.

import "babel-polyfill";
import "whatwg-fetch";

In the webpack configuration remove any ES6 features provided through the ProvidePlugin but leave any other conveniences there (ex. JQuery orz).

new webpack.ProvidePlugin({
    $: "jquery",
    jQuery: "jquery",
    // 'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch',
    // 'Promise': 'exports?global.Promise!es6-promise',
}),

This should give me more rounded ES6 support with manually opting in for each feature I make use of. My hope is that Babel 5/6 will be able to Tree-Shake any unused feature that may otherwise cause bloat by including all of babel-polyfill, perhaps somebody else can speak to that.

like image 71
jpierson Avatar answered Oct 13 '22 17:10

jpierson