问题
I'm using Webpack and Babel to build and transpile my ES6 code. However I am missing important Polyfills when trying to support older browsers. e.g iOS8.
Here's my Webpack.config
const versions = {
v1: './src/js/v1.js',
v2: './src/js/v2.js',
v3: './src/js/v3.js',
};
module.exports = {
entry: versions,
output: {
path: __dirname + '/dist',
filename: '[name].min.js'
},
externals: {
'jquery': 'jQuery'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
}, {
test: /\.hbs$/,
loader: 'handlebars-loader',
}
]
}
}
And my .babelrc
file:
{
"presets": [
["env", {
"targets": {
"browsers": ["last 3 versions", "iOS >= 8"]
}
}]
]
}
Firstly, why isn't this Polyfill being added? And secondly how do I add it? I attempted adding this to my .babelrc
"plugins": ["whatwg-fetch"]
with no luck.
I believe I can add it to the entry of my Webpack config, but that won't work in my instance as I have multiple scripts I am trying to build separately.
Thanks in advance for any help. My depleting head of hair especially is thankful!
回答1:
You can add the resolution of fetch
inside your webpack.config.js
file.
new webpack.ProvidePlugin({
'fetch': 'imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch'
})
Inside your plugins
section.
After that, inside your code, just use fetch
. You won't need to import it whatsoever. Of course, you need imports-loader
and exports-loader
.
回答2:
Babel doesn't add polyfill for web specifications. You can only use polyfills to implement ECMAScript's proposals listed here. It needs to be implemented manually. Github's fetch polyfill or other alternatives can be used.
来源:https://stackoverflow.com/questions/44908044/babel-not-polyfilling-fetch-when-using-babel-preset-env