交叉获取不适用于React Native

时间:2018-10-21 16:56:41

标签: javascript typescript react-native fetch-api

我编写了一个API包装器,该包装器使用访存来执行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

1 个答案:

答案 0 :(得分:1)

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

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; 编译器选项将使TypeScript修补差异,并使用导出分配完成默认导入。但是,由于esModuleInterop明确建议node-ponyfill.js的作者打算支持使用不使用cross-fetch的TypeScript的消费者,因此我想说他们应该修复esModuleInterop以在相同的情况下工作。我看到您已经提交了an issue