0

When I run the following code block, I get the error message "SyntaxError: Cannot use import statement outside a module." I have already installed node-fetch using

npm install node-fetch

What could be going wrong here?

import fetch from 'node-fetch';

fetch('https://api.github.com/users/manishmshiva')
    // Handle success
    .then(response => response.json())  // convert to json
    .then(json => console.log(json))    //print data to console
    .catch(err => console.log('Request Failed', err)); // Catch errors

I installed node-fetch using

npm install node-fetch

after which I was expecting the above code to display either the fetched JSON data or a "Request Failed" error, but instead I get "SyntaxError: Cannot use import statement outside a module" as explained above.

I also get another err0r shown below after including "type": module in the package.json file.

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'node-fetch' imported from e:\i_Chile Profile\1_i_CodeLearn\Javascript Projects\Javascript\ProjectNode\src\fetchAPI.js

I'm using Visual Studio code.

1 Answers1

0

You need to add "type": "module" into your package.json in this case, because you use the import syntax.

  • Hi. I added the "type": "module" in the package.json file but I still get another error. Check it here and tell me what could be going wrong: node:internal/errors:484 ErrorCaptureStackTrace(err); ^ Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'node-fetch' imported from e:\i_Chile Profile\1_i_CodeLearn\Javascript Projects\Javascript\ProjectNode\src\fetchAPI.js – Test-Driven Coder Dec 28 '22 at 04:37
  • Added but not working yet – Hiroshi Nishio Mar 10 '23 at 02:16