ES6 `fetch is undefined`

后端 未结 8 911
太阳男子
太阳男子 2020-12-02 16:27

I\'m building a site with ES6 and Babel.

In a script file, I need to make an ajax call to a service on server. For that I\'m doing like this:

fetch(\         


        
8条回答
  •  既然无缘
    2020-12-02 17:01

    You can also use Webpack's ProvidePlugin with the imports-loader and exports-loader packages as described in this answer, which removes the need to import anything in your code:

    config.plugins = [
        new webpack.ProvidePlugin({
          'fetch': 'imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch'
        })
    ];
    

    At the time of writing there's a compatibility issue with the 3.0.0 version of whatwg-fetch. The workaround is using the following:

    new webpack.ProvidePlugin({
        fetch: 'exports-loader?self.fetch!whatwg-fetch/dist/fetch.umd'
    })
    

提交回复
热议问题