qubyte / fetch-ponyfill

WHATWG fetch ponyfill
MIT License
235 stars 37 forks source link

Imported multiple times causes multiple fetch instances #248

Closed tpluscode closed 4 years ago

tpluscode commented 4 years ago

The title may seem a little off, but the problem I found is that importing fetch-ponyfill multiple times run the bootstrapper for each of those imports.

// module-one.js
import fetchPony from 'fetch-ponyfill'
const { Headers } = fetchPony()

// module-two.js
import fetchPony from 'fetch-ponyfill'
const { Headers } = fetchPony()

Something like above will create two equal, but not the same Headers classes. This makes it impossible to create one headers in stance from the other because it is no recognized by the instanceof check which whatwg-fetch does

Try this sandbox: https://codesandbox.io/s/fervent-fermi-5iews?file=/src/index.js

tpluscode commented 4 years ago

And speaking of whatwg-fetch, why doesn't fetch-ponyfill use native fetch if the browser implements it?

qubyte commented 4 years ago

The answer to your second question is also inadvertently the answer to this issue. The behaviour is intentional because this is a ponyfill (not a polyfill). It’s always meant to ignore the built-in implementation (when available) and as a side effect you’ll get a fresh implementation of fetch each time you call the function in this module.

For the behaviour you want you should probably use whatwg-fetch.

More on ponyfills: https://github.com/sindresorhus/ponyfill

tpluscode commented 4 years ago

Thank you for answering the second question, but pureness does not explain why a different Headers class should be returned on every import. The problem is the bootstrap function which this package exports

Of course, I might take it up with whatwg-fetch to alter how the instances are recognised but I think that the current behavior is against principle of least surprise.

Ah, and Node support is the reason not to use whatwg-fetch directly...