交叉获取不适用于 React Native

cross-fetch doesn't work with React Native

我写了一个 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] }

和 "undefined" 用于 cross_fetch_1.default 或 cross_fetch_1.fetch。

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

据我所知,我正在按预期使用该模块。这可能是什么原因造成的?

我也在这里打开了一个 github 问题:https://github.com/lquixada/cross-fetch/issues/26

在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 作者打算支持使用 TypeScript 而没有 esModuleInterop 的消费者,我认为他们应该修复 browser-ponyfill.js 以在相同的场景下工作.我看到你已经提交了 an issue.