如何使用 webpack 填充 Promise? [英] How can I polyfill Promise with webpack?
问题描述
我正在使用 webpack 来捆绑我的 JavaScript.我依赖于像 popsicle 这样使用 任何承诺.
I'm using webpack to bundle up my JavaScript. I'm depending on modules like popsicle which use any-promise.
这是我的代码:
var popsicle = require('popsicle');
popsicle.get('/').then(function() {
console.log('loaded URL');
});
这在 Promise
可用的浏览器中工作正常,但 IE 11 不提供承诺.所以我想使用 es6-promise 作为 polyfill.
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.
我尝试向我的 webpack.config.js
添加显式 ProvidePlugin
:
I tried adding an explicit ProvidePlugin
to my webpack.config.js
:
plugins: [
new webpack.ProvidePlugin({
'Promise': 'exports?global.Promise!es6-promise'
})
]
但我仍然在 IE 11 中遇到错误:any-promise 浏览器需要 polyfill 或显式注册,例如:require('any-promise/register/bluebird')
.
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');
但是 IE 11 给出了不同的错误:Object 不支持此操作
.
But IE 11 gives a different error: Object doesn't support this action
.
我也试过明确注册es6-promise:
I also tried explicitly registering es6-promise:
require('any-promise/register/es6-promise');
var popsicle = require('popsicle');
这行得通,但我必须在加载 popsicle
的每个文件中都这样做.我只想将 Promise
附加到 window
.
This works, but I have to do it in every single file that loads popsicle
. I want to just attach Promise
to window
.
如何使用 webpack 确保始终定义 window.Promise
?
推荐答案
对于将 babel 与 webpack 结合使用的人:可以使用 babel-polyfill
For people using babel in combination with webpack: you can use babel-polyfill
只需执行 npm install --save "babel-polyfill"
然后将其添加为 webpack.config.js 的入口点:
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']
};
或者,您可以安装 core-js
并仅引用您需要的模块,而不是使用整个 babel-polyfill.
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']
};
这篇关于如何使用 webpack 填充 Promise?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!