Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 2 commits into from Nov 5, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 29 additions & 8 deletions README.md
Expand Up @@ -112,21 +112,21 @@ 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.

`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.
```sh
npm install node-fetch@2
```

Alternatively, you can use the async `import()` function from CommonJS to load `node-fetch` asynchronously:

Expand All @@ -135,6 +135,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:
Expand Down