0

I'm trying to import 'node-fetch'.

import fetch from "node-fetch";

But I seem to get an error.

C:\Users\pat\Documents\GitHub\js\flux\backend\dist\http.js:7
const node_fetch_1 = __importDefault(require("node-fetch"));
                                     ^

Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\pat\Documents\GitHub\js\flux\backend\node_modules\node-fetch\src\index.js from C:\Users\pat\Documents\GitHub\js\flux\backend\dist\http.js not supported.
Instead change the require of index.js in C:\Users\pat\Documents\GitHub\js\flux\backend\dist\http.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (C:\Users\pat\Documents\GitHub\js\flux\backend\dist\http.js:7:38)
    at Object.<anonymous> (C:\Users\pat\Documents\GitHub\js\flux\backend\dist\client.js:11:16)
    at Object.<anonymous> (C:\Users\pat\Documents\GitHub\js\flux\backend\dist\index.js:6:34) {
  code: 'ERR_REQUIRE_ESM'
}

My tsconfig can be found at https://sourceb.in/D5gqXavXF8

HippoBaguette
  • 308
  • 4
  • 15
  • This usually indicates that you shoud change your tsconfig from `"module": "CommonJS",` to e.g. `"module": "ES2020"` but this might break other things if they can't work as ES2020 modules. – apokryfos Jul 23 '22 at 11:39

1 Answers1

1

In your tsconfig.json file add this compiler option

 "esModuleInterop": true,                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */

If this doesn't work then you can do this depending upon your setup

// Do this if using JAVASCRIPT
const fetch = (...args) =>
  import('node-fetch').then(({ default: fetch }) => fetch(...args));

// Do this if using TYPESCRIPT
import { RequestInfo, RequestInit } from 'node-fetch';

const fetch = (url: RequestInfo, init?: RequestInit) =>
  import('node-fetch').then(({ default: fetch }) => fetch(url, init));

Alternatively, you can downgrade the node-fetch package to version 2.6.6 and still use the require syntax. Version 2 of the node-fetch package is built with CommonJS.

You can read more about the breaking changes of the node-fetch package in their GitHub upgrade guide.

Give this blog a read as well