'Importing node-fetch in node project with typescript
How can I import node-fetch package to my node project where I use typescript.
I tried it in many ways... right now I am on:
const fetch = (...args) =>
import("node-fetch").then(({ default: fetch }) => fetch(...args));
But I have 2 errors:
Cannot redeclare block-scoped variable 'fetch'.
and
A spread argument must either have a tuple type or be passed to a rest parameter.
When I change const fetch = to any other name like const fetchIt = it fixes first error but... do I really have to change that? How can I import node-fetch package in normal way where I can use fetch() method? In React I just make
import fetch from 'node-fetch';
and everything works fine... why is that so hard in node projects?
Solution 1:[1]
If you have conflicts with a global fetch, this suggests that you have the DOM lib in your tsconfig.json enabled, e.g.:
{
"compilerOptions": {
"lib": ["es2021", "dom"]
}
}
I would suggest removing this. For a NodeJS project, have a look at this answer for the suggested tsconfig.json settings depending on the NodeJS version.
After this, you will be able to import fetch as you wrote in your question and assign it to a variable named fetch, without conflicting names:
import fetch from 'node-fetch';
Alternative solution: If you need to work with 3rd party libs which are built with a browser focus and require a global fetch, have a look at the isomorphic-fetch module, which adds fetch as global function.
You will need to import it once so that fetch is available globally:
import 'isomorphic-fetch';
In this case, the compiler options of your tsconfig.json should contain the dom lib.
Update 2022-02-04
Newer NodeJS versions ship a native fetch API now, so above will no longer be necessary going forward. See here and here for more information.
Solution 2:[2]
Update:
My original post below is all true. I have been able to get it to work, however, without having to switch to ESM modules. Here is what's working in my code (based on the third code snippet in the following post: https://github.com/node-fetch/node-fetch/issues/1279#issuecomment-915063354)
// eslint-disable-next-line no-new-func
const importDynamic = new Function('modulePath', 'return import(modulePath)');
const fetch = async (...args:any[]) => {
const module = await importDynamic('node-fetch');
return module.default(...args);
};
Original Post:
The Cannot redeclare block-scoped variable 'fetch' error is because you're declaring a const fetch variable, and then reusing the name "fetch" as the object-destructured parameter to the then() callback later in the line.
So, changing the line to read as follows clears up that error:
const fetch = (...args) => import("node-fetch").then(module => module.default(...args));
As for the other error (A spread argument must either have a tuple type or be passed to a rest parameter.), one possible way to solve this would be to actually import the correct argument types for the fetch() call, then substitute in the above code snippet as appropriate, like this:
import { RequestInfo, RequestInit } from 'node-fetch';
const fetch = (url:RequestInfo, init?:RequestInit) => import('node-fetch').then(module => module.default(url, init));
Unfortunately, while that seems to satisfy the TypeScript compiler, I'm finding in my own code that the runtime still doesn't work (throws an ERR_REQUIRE_ESM) because my TypeScript config is currently using CommonJS modules rather than an ESM format.
See https://github.com/node-fetch/node-fetch/issues?q=ERR_REQUIRE_ESM for several open issues in the node-fetch package related to this problem.
Essentially, the node-fetch maintainers are suggesting those of us using TypeScript need to convert to ESM modules, away from CommonJS (see https://github.com/node-fetch/node-fetch/issues/1397#issuecomment-978092116 and subsequent comments).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
