Babel not Polyfilling Fetch when using babel-preset-env

Viewed 14465

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!

4 Answers

First of all, you're trying to add a polyfill for a web/DOM standard, not a JS polyfill. Babel only handles transpiling and polyfilling the standard ECMAScript language features, it does not handle web/browser specifications, like fetch. So you shouldn't load it with the babel loader in Webpack.

I've tried the other solutions offered here myself, but none of them works anymore. What worked for me was simply installing the package npm i whatwg-fetch --save-dev then adding it in the entry configuration option field, like this:

module.exports = {
  entry: ["whatwg-fetch", "./src/yourapp.js"]
}

Where ./src/yourapp.js should be the entry point of your app. I'm posting this in case someone will run into the same issue and the other solutions won't work.

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.

In my case Error was ReferenceError: fetch is not defined

I had the error on firebase with global this and server rendering, following some solutions, I ended up with adding a plugin in webpack then rebuilding I ended with a bunch of errors in the type of "multi ..." which are basically that there are multiple definitions of that library

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

AND FINALLY IN RESOLVE section

mainFields: ['main']
Related