I'm using a loader package to which I pass the name of a loadee module and it require()
s it.
The loader uses CJS's require()
to dynamically require the loadee, but the loadee is an ES module. Because of this Node.js throws an error.
Error [ERR_REQUIRE_ESM]: require() of ES Module LOADEE from LOADER not supported.
Instead change the require of LOADEE in LOADER to a dynamic import() which is available in all CommonJS modules.
Neither the loader or the loadee are managed by me, so I can't modify them. I can't avoid using them either.
I can of course write an intermediary loadee, written in CJS (so the loader can load it), which then loads the true loadee and passes it back to the loader. But I don't know how to do it, since the dynamic import()
is async (returns a promise), but the loader's require()
is sync and expects the loaded module immediately.
Is there anything else I can do to make this thing work?
Example to show what's happening
In case the description I gave is not clear enough, I'm trying to post some minimal snippets of code to show what's happening:
LOADER (CJS; not written by me)
module.exports = function(pkg) {
const x = require(pkg)
console.log(x)
}
LOADEE (ES Module; not written by me)
default export const x = 1
./index.js (this one is mine: I can choose CJS or ES Module or anything else)
import load from 'LOADER'
load('LOADEE')
When I run node ./index.js
this is what I get:
Error [ERR_REQUIRE_ESM]: require() of ES Module LOADEE from LOADER not supported.
Instead change the require of LOADEE in LOADER to a dynamic import() which is available in all CommonJS modules.
Similar questions
I already found similar questions on stack overflow. For instance:
Error: require() of ES modules is not supported when importing node-fetch
Error [ERR_REQUIRE_ESM]: require() of ES Module not supported
They explain how to use import()
to dynamically import a module. But that doesn't help me since I cannot change the require()
call in the loader and don't know how to wrap it with an async dynamic import()
.
Is there anything I can do to make this thing work?