【问题标题】:cross-fetch doesn't work with React Native交叉获取不适用于 React Native
【发布时间】:2019-03-25 20:14:06
【问题描述】:

我编写了一个 API 包装器,它使用 fetch 来执行 API 请求。因为我希望该模块与浏览器、Node 和 React Native 兼容,所以我使用cross-fetch。现在,如果我用 Node 测试它,它可以完美运行,但是如果我在 React Native 中使用包装器,如果失败并出现以下错误:TypeError: undefined is not a function (evaluating 'cross_fetch_1.default(url, init)')。如果我打印 cross_fetch_1 的类型,我会得到:

{ [Function]
  polyfill: true,
  Response: { [Function: Response] error: [Function], redirect: [Function] },
  Request: [Function: Request],
  Headers: [Function: Headers] }

cross_fetch_1.default 或 cross_fetch_1.fetch 的“未定义”。

该库是用 Typescript 开发的,因此 cross_fetch_1 变量由 TS 编译器创建。你可以在这里https://github.com/tgamauf/onetimesecret-api/blob/1b8edff66bde11807c8ff7d29030b4d3e6661277/lib/request.ts#L150找到Typescript代码,在这里https://github.com/tgamauf/onetimesecret-api/blob/1b8edff66bde11807c8ff7d29030b4d3e6661277/lib/request.js#L179找到编译好的JS。

据我所知,我正在使用应该使用的模块。这是什么原因造成的?

我还在这里打开了一个关于此的 github 问题:https://github.com/lquixada/cross-fetch/issues/26

【问题讨论】:

  • 如果您要同时提交有关同一问题的 Stack Overflow 问题和问题报告,请相互链接以帮助防止重复工作。
  • 你说得对,我已经添加了问题的链接!

标签: javascript typescript react-native fetch-api


【解决方案1】:

在React Native中导入cross-fetch时,React Native模块捆绑器根据node_modules/cross-fetch/package.jsonbrowser字段选择node_modules/cross-fetch/dist/browser-ponyfill.js;我相信这是配置here。而node_modules/cross-fetch/dist/browser-ponyfill.js 仅提供导出分配,而不是默认导出:

if (typeof module === 'object' && module.exports) {
module.exports = fetch;
}

对比node_modules/cross-fetch/dist/node-ponyfill.js,它既有导出分配又有默认导出:

module.exports = exports = fetch;
exports.fetch = fetch;
exports.Headers = nodeFetch.Headers;
exports.Request = nodeFetch.Request;
exports.Response = nodeFetch.Response;

// Needed for TypeScript.
exports.default = fetch;

在您的项目中启用 esModuleInterop 编译器选项将使 TypeScript 修补差异并使用导出分配完成您的默认导入。但是,由于node-ponyfill.js 明确表明cross-fetch 作者打算支持在没有esModuleInterop 的情况下使用TypeScript 的消费者,我想说他们应该修复browser-ponyfill.js 以在相同的情况下工作。我看到你已经提交了an issue

【讨论】:

  • 激活esModuleInterop 解决了我的问题。谢谢你,马特!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-24
  • 1970-01-01
  • 2020-05-27
  • 2018-07-20
  • 2021-08-16
  • 2016-11-04
  • 2021-02-19
相关资源
最近更新 更多