ReactJS with Fetch on older browsers

2019-07-04 18:52发布

问题:

I am implementing React JS, with Webpack and Babel. However, I am having trouble getting Fetch to work with IE 11.

I have the following in my .babelrc file:

{
  "presets" : ["env", "stage-0", "react"]
}

and the following in my webpack.config.js file:

var webpack = require('webpack');
var path = require('path');

var DIST_DIR = path.resolve(__dirname, 'dist');
var SRC_DIR = path.resolve(__dirname, 'src');

var config = {
  entry: {
    bundle: [
      'babel-polyfill',
      SRC_DIR + '/app/index.js',
    ]
  },
  output: {
    path: DIST_DIR + '/public/js',
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        include: SRC_DIR,
        loader: 'babel-loader'
      }
    ]
  }
};

module.exports = config;

From my understanding implementing babel-preset-env, stage-0, and babel-polyfill should have allowed for the Fetch API to be transpiled into something older browsers could understand. Is there something else that I am missing?

回答1:

fetch isn't part of EcmaScript but its part of the web platform. Babel is only a compiler to write the latest Javascript. If you want to use fetch in older browsers you need a polyfill like this one

Fetch API: read more



回答2:

fetch must be made available by the browser you use and is not included in babel-polyfill. If your browser doesn't support fetch, you can either fall back to using XMLHttpRequest or use a polyfill such as isomorphic-fetch.