Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 265
Sowam Avatar asked Dec 04 '25 05:12

Sowam


1 Answers

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.

like image 61
qqilihq Avatar answered Dec 05 '25 19:12

qqilihq