Mocha "--require" ESM Errors - ERR_REQUIRE_ESM with Setup Files
Mocha’s --require uses CommonJS require(). If the setup file (or what it imports) is ESM-only, Node throws ERR_REQUIRE_ESM. Newer Mocha/Node use --import/--loader to register ESM setup instead.
What this error means
Mocha fails at startup with ERR_REQUIRE_ESM pointing at a --require’d setup file or babel/ts register hook. The tests never run because the bootstrap module cannot be require()d.
Error [ERR_REQUIRE_ESM]: require() of ES Module
/app/test/setup.mjs from mocha not supported.
Instead change the require of setup.mjs to a dynamic import().Common causes
ESM setup file loaded via --require
--require ./test/setup.mjs uses CommonJS require(), which cannot load an ESM module. Node rejects it with ERR_REQUIRE_ESM.
A register hook that is ESM-only
Babel/TS register hooks or polyfills shipped as ESM fail the same way when pulled in through --require.
How to fix it
Use --import for ESM setup (Node 20+)
--import registers an ESM module before tests, replacing CommonJS --require for ESM setup files.
// .mocharc.json
{
"import": ["./test/setup.mjs"],
"spec": "test/**/*.test.mjs"
}Or keep the setup CommonJS
- If you must use
--require, write the setup as CommonJS (.cjs). - On older Node, use
--loader/--experimental-loaderfor ESM register hooks. - Match Mocha and Node versions that support
--import.
How to prevent it
- Use
--importfor ESM setup files on modern Node/Mocha. - Keep
--requiretargets CommonJS (.cjs). - Align Node and Mocha versions with your module strategy.