Skip to content
Latchkey

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.

Mocha output
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
// .mocharc.json
{
  "import": ["./test/setup.mjs"],
  "spec": "test/**/*.test.mjs"
}

Or keep the setup CommonJS

  1. If you must use --require, write the setup as CommonJS (.cjs).
  2. On older Node, use --loader/--experimental-loader for ESM register hooks.
  3. Match Mocha and Node versions that support --import.

How to prevent it

  • Use --import for ESM setup files on modern Node/Mocha.
  • Keep --require targets CommonJS (.cjs).
  • Align Node and Mocha versions with your module strategy.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →