在旧浏览器上使用 Fetch 的 ReactJS

2022-01-20 00:00:00 reactjs fetch javascript webpack babeljs

我正在使用 Webpack 和 Babel 实现 React JS.但是,我无法让 Fetch 与 IE 11 一起使用.

我的 .babelrc 文件中有以下内容:

<代码>{预设":[env",stage-0",react"]}

以及我的 webpack.config.js 文件中的以下内容:

var webpack = require('webpack');var path = require('path');var DIST_DIR = path.resolve(__dirname, 'dist');var SRC_DIR = path.resolve(__dirname, 'src');变量配置 = {入口: {捆: ['babel-polyfill',SRC_DIR + '/app/index.js',]},输出: {路径:DIST_DIR + '/public/js',文件名:'bundle.js'},模块: {装载机:[{测试:/.jsx?$/,包括:SRC_DIR,加载器:'babel-loader'}]}};module.exports = 配置;

根据我的理解,实现 babel-preset-env、stage-0 和 babel-polyfill 应该允许将 Fetch API 转换为旧浏览器可以理解的东西.我还有什么遗漏的吗?

解决方案

fetch 不是 EcmaScript 的一部分,而是 web 平台 的一部分.Babel 只是一个编写最新 Javascript 的编译器.如果你想在旧版浏览器中使用 fetch 你需要一个像 this one

Fetch API:阅读更多p>

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?

解决方案

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

相关文章