How can I tell node that my script is not a module?
Apparently if anything in node_modules is a module node will think my script is a module and fail with: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module:
Asked
Active
Viewed 114 times
0

pguardiario
- 53,827
- 19
- 119
- 159
-
could you explain a bit more what you are trying to do? where is your script located? what do you have in package.json? – germanio Sep 17 '21 at 03:16
-
The package.json is for a react app, but I just want to run a simple node script from the same folder without having to delete node_modules every time. – pguardiario Sep 17 '21 at 03:20
-
which node version are you using, and what your script looks like? – Cuong Vu Sep 17 '21 at 03:23
-
@Cuong - v14.16.1 and it fails at `const fetch = require('node-fetch')` – pguardiario Sep 17 '21 at 03:40
-
Probable duplicates https://stackoverflow.com/questions/61670459/nodejs-must-use-import-to-load-es-module, https://stackoverflow.com/questions/57169793/error-err-require-esm-how-to-use-es6-modules-in-node-12, https://stackoverflow.com/questions/61905905/error-err-require-esm-must-use-import-to-load-es-module – Salvino D'sa Sep 17 '21 at 03:56
1 Answers
1
As you mentioned you are using node-fetch
, and node v14.16.1. Inside node-fetch
documentation
node-fetch is an ESM-only module - you are not able to import it with require. We recommend you stay on v2 which is built with CommonJS unless you use ESM yourself. We will continue to publish critical bug fixes for it.
So you have 2 options here:
- Continue using
node-fetch
3, and change toimport fetch from 'node-fetch';
. You may need to change your script to .mjs. - Downgrade to
node-fetch
2 to be able to userequire
.

Cuong Vu
- 3,423
- 14
- 16