ES6“提取未定义”

ES6 `fetch is undefined`

本文关键字:提取未定义 未定义 提取 ES6      更新时间:2024-03-06

我正在用ES6和Babel构建一个站点。

在脚本文件中,我需要对服务器上的服务进行ajax调用。为此,我这样做:

fetch('url').then(
    response => response.json()
).then(
    supervisoryItems => doSomething(supervisoryItems)
)

在Google Chrome中,这很好,但在Firefox或IE上不起作用(我收到错误fetch is undefined)。在谷歌上搜索我发现这应该可以修复它:

import promise from 'es6-promise'
promise.polyfill()

遗憾的是,这并没有改变任何事情,我也有同样的问题。有什么帮助吗?

您需要将"同构获取"模块添加到"package.json"中,然后导入它。

npm install --save isomorphic-fetch es6-promise

然后在你的代码

import "isomorphic-fetch"

请参阅https://www.npmjs.com/package/isomorphic-fetch

我将使用如下两个cdn:

<script src="//cdn.jsdelivr.net/bluebird/3.5.0/bluebird.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.js"></script>

Babel polyfill(http://babeljs.io/#polyfill)目前在polyfill中不包括fetch。不过我想加上它。

但是耶可以用https://github.com/github/fetch

您还可以将Webpack的ProviderPlugin与本答案中描述的导入加载程序和导出加载程序包一起使用,这样就不需要导入代码中的任何内容:

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

在撰写本文时,whatwg-fetch的3.0.0版本存在兼容性问题。解决方法如下:

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

我更喜欢使用isomorphic-unfetch而不是isomorphic-fetch,因为它可以像ponyfill而不是polyfill一样工作。

不同之处在于,它不会影响代码的其余部分,而且它对您所拥有的依赖关系更透明。


安装:

yarn add isomorphic-unfetch

用法:

// using ES6 modules
import fetch from 'isomorphic-unfetch';
// using CommonJS modules
var fetch = require('isomorphic-unfetch');

昨晚刚刚经历了这一切。最后,在尝试了各种方法后,解决方案相当简单:

fetch('url').then(
response => response.json()
).then(
supervisoryItem => doSomething(supervisoryItem)
)

成为

window.fetch('url').then(
response => response.json()
).then(
supervisoryItem => doSomething(supervisoryItem)
)

TL;DR fetch(stuff)应为窗口。fetch(stoff)编辑这对我在Chrome 上有效

Javascript中添加的每个新功能都有浏览器支持。您可以在上查看浏览器支持https://caniuse.com/#feat=fetch

按照以下2个步骤在IE11 上使用fetch

步骤1:安装3个软件包

npm i whatwg-fetch @babel/polyfill es6-promise --save

@babel/polyfill-在babel中使用polyfill

whatwg获取-包括获取功能

es6 promise-fetch polyfill包括IE11 也不支持的promise

步骤2:在webpack.config中添加入口点

条目:["whatwg fetch","@babel/polyfill","./src/js/index.js"]

require("es6-promise").polyfill();
const config = {
  entry: [ "whatwg-fetch", "@babel/polyfill", "./src/js/index.js"],
  output: {
    filename: 'bundle.js'
  },
  module: {
    rules : [
      {
        test: /'.js$/,
        exclude: /node_modules/,
        use: ['babel-loader']
      },
      {
        test: /'.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  }
};
module.exports = config;

Window.fetch或fetch是相同的。。。从技术上讲,fetch()是Window对象的全局方法