docs: Improve clarity of "Loading and configuring" (#1323)

* docs: Improve clarity of "Loading and configuring"

* Update README.md

Co-authored-by: Linus Unnebäck <linus@folkdatorn.se>

Co-authored-by: Linus Unnebäck <linus@folkdatorn.se>
This commit is contained in:
Ambrose Chua 2021-11-05 20:33:22 +08:00 committed by GitHub
parent a3a5b6316e
commit 37ac459cfd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 29 additions and 8 deletions

View File

@ -111,22 +111,22 @@ npm install node-fetch
## Loading and configuring the module
### ES Modules (ESM)
```js
import fetch from 'node-fetch';
```
If you want to patch the global object in node:
### CommonJS
```js
import fetch from 'node-fetch';
`node-fetch` from v3 is an ESM-only module - you are not able to import it with `require()`.
if (!globalThis.fetch) {
globalThis.fetch = fetch;
}
If you cannot switch to ESM, please use v2 which remains compatible with CommonJS. Critical bug fixes will continue to be published for v2.
```sh
npm install node-fetch@2
```
`node-fetch` is an ESM-only module - you are not able to import it with `require`. We recommend you stay on v2 which is built with CommonJS unless you use ESM yourself. We will continue to publish critical bug fixes for it.
Alternatively, you can use the async `import()` function from CommonJS to load `node-fetch` asynchronously:
```js
@ -134,6 +134,27 @@ Alternatively, you can use the async `import()` function from CommonJS to load `
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
```
### Providing global access
To use `fetch()` without importing it, you can patch the `global` object in node:
```js
// fetch-polyfill.js
import fetch from 'node-fetch';
if (!globalThis.fetch) {
globalThis.fetch = fetch;
globalThis.Headers = Headers;
globalThis.Request = Request;
globalThis.Response = Response;
}
// index.js
import './fetch-polyfill'
// ...
```
## Upgrading
Using an old version of node-fetch? Check out the following files: