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 diminishing head of hair is especially thankful!
@babel/preset-env is a smart preset that allows you to use the latest JavaScript without needing to micromanage which syntax transforms (and optionally, browser polyfills) are needed by your target environment(s). This both makes your life easier and JavaScript bundles smaller!
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 ).
So long story short, just using babel is not enough for your application to work because all the latest Javascript features are not supported in all browsers. So to fix this problem, we need to use a polyfill.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With