4

I'm trying to run this script

const fetch = require('node-fetch');

function test() {
  fetch('https://google.com')
    .then(res => res.text())
    .then(text => console.log(text))
}

test();

But i get this error

This expression is not callable. Type 'typeof import("(...)/node_modules/node-fetch/@types/index")' has no call signatures.ts(2349)

although it works when i use import

import fetch from 'node-fetch';

why and how to fix it?

Oba Api
  • 231
  • 1
  • 3
  • 10
  • 3
    Most likely the default export is on the `default` prop of the module. How `const {default as fetch} = require('node-fetch')` resolve? – spender Sep 01 '21 at 11:22
  • Sorry, i tried const { fetch as fetch } = require('node-fetch'); but i got 'Module '"node-fetch"' has no exported member 'fetch'. Did you mean to use 'import fetch from "node-fetch"' instead?ts(2614)' – Oba Api Sep 01 '21 at 11:30
  • 1
    Also the npm page mentions: 'node-fetch is an ESM-only module - you are not able to import it with require.' i'm still trying to do it, because my file has also require to load json. How would you solve this? make everything import? – Oba Api Sep 01 '21 at 11:35
  • Why using `require` if you can use `import`? I also suppose you can `import` jsons, but if it fails, you can use `import` for modules and `require()` for json files – Nikita Ivanov Sep 01 '21 at 11:52
  • @ObaApi You said "I tried const { fetch as fetch } = require('node-fetch');". That's not what I wrote. Specifically, how does `const {default as fetch} = require('node-fetch')` work out for you? – spender Sep 01 '21 at 12:12
  • Thanks, i'm getting this error: ':' expected.ts(1005) Duplicate identifier 'as'.ts(2300) – Oba Api Sep 01 '21 at 13:23
  • 4
    @ObaApi Oops. Sorry, I got confused with `import` syntax. I meant `const {default : fetch} = require('node-fetch')` – spender Sep 01 '21 at 13:31
  • Actually const {default as fetch} = require('node-fetch') also works. I still try to find a way to load json credentials in an easy way in a module file that does not allow require. I've made new post for this: https://stackoverflow.com/questions/69014923/is-there-an-easy-way-to-load-json-in-a-node-module – Oba Api Sep 01 '21 at 13:53
  • @spender that worked for me and axios, so I posted it as an answer – AncientSwordRage Nov 27 '21 at 22:28

1 Answers1

6

As per spender's comment, you can change the require to use this destructuring:

const {default : fetch} = require('node-fetch');

This has worked for me in a similar situation (using axios in node, which has a similar API)

AncientSwordRage
  • 7,086
  • 19
  • 90
  • 173