developit / unfetch

🐕 Bare minimum 500b fetch polyfill.
https://npm.im/unfetch
MIT License
5.71k stars 201 forks source link

Webpack: isomorphic-unfetch breaks node build due to wrong esm interop. #122

Closed ealmansi closed 4 years ago

ealmansi commented 5 years ago

Bug Report

Requiring isomorphic-unfetch in a project built with Webpack targeting node leads to broken code. The issue is due to wrong interoperation between cjs & esm by isomorphic-unfetch.

How to Reproduce

$ mkdir bug-repro && cd bug-repro
$ yarn init -y
$ yarn add isomorphic-unfetch webpack webpack-cli
$ echo "require('isomorphic-unfetch')('https://goo.gl').then(console.log)" > index.js
$ npx webpack index.js --target node --mode development
$ node dist/main.js

Expected Result

> Response {
  ...
}

Actual Result

webpack:///./node_modules/isomorphic-unfetch/index.js?:3
        return __webpack_require__(/*! node-fetch */ "./node_modules/node-fetch/lib/index.mjs")(url.replace(/^\/\//g,'https://'), opts);
                                                                                               ^

TypeError: __webpack_require__(...) is not a function

Context

In file packages/isomorphic-unfetch/index.js, you can find the following code: require('node-fetch'). However, the package node-fetch exposes the function fetch as the default export in an ESM module [1]. The correct way of requiring a default export from CommonJS is require('node-fetch').default; see [2].

[1] https://github.com/bitinn/node-fetch/blob/master/src/index.js#L34 [2] https://github.com/bitinn/node-fetch/issues/450#issuecomment-462695245

Environment

→ lsb_release -a
Description:    Ubuntu 18.04.2 LTS
→ node --version
v10.15.3
→ yarn --version
1.15.2
→ npm ls isomorphic-unfetch webpack
bug-repro@1.0.0
├── isomorphic-unfetch@3.0.0 
└── webpack@4.39.2
ivan-kleshnin commented 5 years ago

I'm getting

You must provide the URL of lib/mappings.wasm by calling SourceMapConsumer.initialize({ 'lib/mappings.wasm': ... }) before using SourceMapConsumer
    at readWasm

With nodemon + unfetch + slonik. Probably related to this issue.

karlhorky commented 5 years ago

I had a similar issue to @ivan-kleshnin when using Slonik with Next.js in my project:

https://github.com/karlhorky/next.js-with-slonik

Fixed it in this commit by switching isomorphic-unfetch to cross-fetch, like @gabiseabra in https://github.com/emcasa/react-starter/pull/12:

https://github.com/karlhorky/next.js-with-slonik/commit/a61f47949aa367020c1b0d2f6d657e63702cb6a4

karlhorky commented 5 years ago

Awesome, thanks @danieltodonnell!

danieltodonnell commented 5 years ago

I made a mistake and commented in the wrong issue :(

I meant to write "we will investigate" in the issue in faunadb that was affected by this issue.

developit commented 4 years ago

Released in 4.2.0. Sorry for the super long wait!