Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I polyfill Promise with webpack?

I'm using webpack to bundle up my JavaScript. I'm depending on modules like popsicle which use any-promise.

Here's my code:

var popsicle = require('popsicle'); popsicle.get('/').then(function() {   console.log('loaded URL'); }); 

This works fine in browsers where Promise is available, but IE 11 does not provide Promise. So I want to use es6-promise as a polyfill.

I tried adding an explicit ProvidePlugin to my webpack.config.js:

plugins: [   new webpack.ProvidePlugin({     'Promise': 'exports?global.Promise!es6-promise'   }) ] 

But I still get the error in IE 11: any-promise browser requires a polyfill or explicit registration e.g: require('any-promise/register/bluebird').

I tried explicitly attaching a global:

global.Promise = global.Promise || require('es6-promise'); 

But IE 11 gives a different error: Object doesn't support this action.

I also tried explicitly registering es6-promise:

require('any-promise/register/es6-promise'); var popsicle = require('popsicle'); 

This works, but I have to do it in every single file that loads popsicle. I want to just attach Promise to window.

How can I ensure window.Promise is always defined, using webpack?

Full repo demo here.

like image 706
Wilfred Hughes Avatar asked Aug 15 '16 18:08

Wilfred Hughes


People also ask

What is shimming in webpack?

The webpack compiler can understand modules written as ES2015 modules, CommonJS or AMD. However, some third party libraries may expect global dependencies (e.g. $ for jQuery ). The libraries might also create globals which need to be exported.

Is Babel a polyfill?

Babel includes a polyfill that includes a custom regenerator runtime and core-js. This will emulate a full ES2015+ environment (no < Stage 4 proposals) and is intended to be used in an application rather than a library/tool. (this polyfill is automatically loaded when using babel-node ).


2 Answers

For people using babel in combination with webpack: you can use babel-polyfill

Just do npm install --save "babel-polyfill" and then add it as an entry point in your webpack.config.js:

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

Or, instead of using the entire babel-polyfill you can install core-js and reference only the module you need.

module.exports = {    entry: ['core-js/stable/promise', './app/js'] }; 
like image 136
Jeroen Pelgrims Avatar answered Sep 27 '22 22:09

Jeroen Pelgrims


Option that worked for me. es6-promise-promise is designed to be included directly to the webpack builds. So:

plugins: [   new webpack.ProvidePlugin({     Promise: 'es6-promise-promise'   }) ] 
like image 20
asiniy Avatar answered Sep 27 '22 23:09

asiniy