Problem with loading "ES module" when importing in node js [duplicate]
There are two kinds of modules in nodejs - the older CommonJS which uses require()
to load other CommonJS modules and the newer ESM which uses import
to load other ESM modules? There are a few ways to mix and match module types, but that requires some additional knowledge and it is always easier if all the modules in your project are of the same type. So, for us to offer specific advice on your project, we need to know everything that you're trying to use in your project and what module type they all are.
The specific error you first report in your question is because you are trying to use import
to load other modules from a file that nodejs is assuming is a CommonJS module and it will not allow that. If everything you are programming with is CommonJS modules, then switch to use require()
to load your module instead of import
. But, if everything isn't CommonJS modules, then it may be a bit more complicated.
The file extension (.mjs
or .cjs
) can force a module type or the "type": xxx
in package.json can force a type. By default, with neither of those in place nodejs assumes your top level module with a .js
extension is a CommonJS module where you would use require()
to load other CommonJS modules.
The second error you get when you tried to force your top level module to be an ESM module makes it sounds like the module you are trying to import is a CommonJS module.
So, if I had to guess, I'd say the file you are trying to import is a CommonJS file and therefore, life would be easiest if you made your top level file CommonJS. To do that, remove the "type": "module"
from package.json and change your import someModule
to require(someModule)
instead. This will attempt to just let everything be CommonJS modules.