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

1
  • 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. Commented Jul 23, 2022 at 11:39

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

9 Comments

Thanks for the response! I already have this enabled by default, so this shouldn't be the problem or the solution.
@HippoBaguette can you share your tsconfig.json here?
In your package.json file, what is the value of the "type" property? "commonjs" or "module"
I do not have a "type" property set, so i would assume perhaps the default?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.