From c77599a4eeee830c7b35b828b9cd5923166f3af5 Mon Sep 17 00:00:00 2001 From: Ambrose Chua Date: Thu, 30 Sep 2021 09:26:11 +0800 Subject: [PATCH 1/2] docs: Improve clarity of "Loading and configuring" --- README.md | 38 ++++++++++++++++++++++++++++++-------- 1 file changed, 30 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index aa2e2af63..ac9e674e0 100644 --- a/README.md +++ b/README.md @@ -112,21 +112,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. -`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 uninstall node-fetch +npm install node-fetch@2 +``` Alternatively, you can use the async `import()` function from CommonJS to load `node-fetch` asynchronously: @@ -135,6 +136,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: From bc474bcefeb6a828d0fe1261ce302b062956e83d Mon Sep 17 00:00:00 2001 From: Ambrose Chua Date: Fri, 5 Nov 2021 18:58:56 +0800 Subject: [PATCH 2/2] Update README.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Linus Unnebäck --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index ac9e674e0..80cfaa420 100644 --- a/README.md +++ b/README.md @@ -125,7 +125,6 @@ import fetch from 'node-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 uninstall node-fetch npm install node-fetch@2 ```