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?

9
  • 3
    Most likely the default export is on the default prop of the module. How const {default as fetch} = require('node-fetch') resolve? Commented Sep 1, 2021 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)' Commented Sep 1, 2021 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? Commented Sep 1, 2021 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 Commented Sep 1, 2021 at 11:52
  • 4
    @ObaApi Oops. Sorry, I got confused with import syntax. I meant const {default : fetch} = require('node-fetch') Commented Sep 1, 2021 at 13:31

1 Answer 1

7

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)

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.