Babel not Polyfilling Fetch when using babel-preset-env

前端 未结 4 422
夕颜
夕颜 2020-12-20 13:25

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

相关标签:
4条回答
  • 2020-12-20 13:50

    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']
    
    0 讨论(0)
  • 2020-12-20 13:51

    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.

    0 讨论(0)
  • 2020-12-20 13:57

    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.

    0 讨论(0)
  • 2020-12-20 14:00

    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.

    0 讨论(0)
提交回复
热议问题