skip to content

In a Jest 30 suite, why does a test that imports an ESM-only package from node_modules fail to load, and how do you fix it?

level: seniorimportance: should knowfreq 48%

answer

  1. node_modules is skipped by default
  2. a negative lookahead allowlist
  3. the transformer must emit CommonJS
  4. require(esm) needs a Node flag

basics

~20 s

transformIgnorePatterns defaults to skipping /node_modules/, so the package's import and export syntax is never compiled and loading it as CommonJS fails. Allowlist it, for example '/node_modules/(?!(package-a)/)', or on Node 24.9+ run Jest with --experimental-vm-modules to require() it natively.

solid answer

~40 s

A typical suite compiles tests to CommonJS, but `transformIgnorePatterns` defaults to `["/node_modules/", "\\.pnp\\.[^\\/]+$"]`, so no transformer touches a dependency. When that dependency ships only ES modules, Jest 30.5.2 stops with `Must use import to load ES Module: .../package-a/index.js` and lists the options. The classic fix is an allowlist: `'/node_modules/(?!(package-a|@scope/pkg-b)/)'`, written as one pattern, plus a transformer that turns those files into CommonJS, which for `babel-jest` means a project-wide Babel config that reaches `node_modules`. The newer fix: on Node 24.9 or later, run Jest with `--experimental-vm-modules` and Jest can `require()` the ES module without transforming it. Check two things: overlapping patterns cancel each other, and under `jsdom` the `browser` export condition may pick a different build.

code

javascript · 10 lines
javascript
// jest.config.js
const {defineConfig} = require('jest');

module.exports = defineConfig({
  transform: {
    '\\.[jt]sx?$': ['babel-jest', {rootMode: 'upward'}],
  },
  // one pattern with an alternation: skip node_modules except these two
  transformIgnorePatterns: ['/node_modules/(?!(package-a|@scope/pkg-b)/)'],
});

go deeper

for a junior

Recall that Jest skips node_modules when transforming and that an ESM-only dependency therefore needs configuration.

for a middle

Explain the default transformIgnorePatterns, how a negative lookahead allowlists a package, and why the transformer must still emit CommonJS.

for a senior

Diagnose the failure end to end: read the error, confirm patterns with --showConfig, avoid cancelling patterns, and know when require(esm) or the jsdom export condition is the real cause.

for a principal

Set the suite's module strategy, transform-on-demand or require(esm) on a pinned Node release, and weigh experimental ESM support against a fleet of older Node versions.

## Why the package fails Most Jest suites run **CommonJS**: `babel-jest` (or another transformer) rewrites `import` statements in your tests and sources into `require()` calls. Dependencies are a different story. `transformIgnorePatterns` lists regexes matched against the **full path** of every file before transformation; a file matching any of them is loaded untouched. Its default is: ```js ["/node_modules/", "\\.pnp\\.[^\\/]+$"] ``` So a package that ships only `export` and `import` syntax reaches Jest's CommonJS loader as-is. Releases before Jest 30.5.0 reported this with the generic `Jest encountered an unexpected token` message; in Jest 30.5.2 the failure reads: ```plaintext Must use import to load ES Module: /repo/node_modules/package-a/index.js The file contains ESM syntax (import/export) that could not be executed as CommonJS. Either: - Configure a transform (e.g. babel-jest) that compiles this file to CommonJS (see https://jestjs.io/docs/code-transformation) - If the file is in "node_modules", allow it to be transformed by adjusting "transformIgnorePatterns" (see https://jestjs.io/docs/configuration#transformignorepatterns-arraystring) - Use Node v24.9+ where Jest supports require(esm) natively (see https://jestjs.io/docs/ecmascript-modules#require-of-esm) ``` The application's own build is unaffected, because the bundler compiles or loads ES modules itself; Jest does not read the bundler's config. ## Fix 1: let the package be transformed 1. **Allowlist the package** with a negative lookahead, so `node_modules` is still skipped except for the named packages: ```js transformIgnorePatterns: ['/node_modules/(?!(package-a|@scope/pkg-b)/)'] ``` 2. **Make sure a transformer emits CommonJS for those files.** With `babel-jest` that means a Babel configuration that applies to files inside `node_modules`, normally a project-wide `babel.config.js` with a preset that converts modules; the rules for which Babel config file reaches which folder are the Babel lesson's subject. In a monorepo, `['babel-jest', {rootMode: 'upward'}]` lets each package find the root config. 3. **Clear stale output** with `jest --clearCache` if results do not change after a Babel edit, and confirm the effective patterns with `jest --showConfig`. Pitfalls in this route: - **Patterns combine with OR.** A file is skipped if it matches *any* pattern, so `['/node_modules/(?!foo/)', '/node_modules/(?!bar/)']` skips both packages: each pattern matches the other's path. Write one pattern with an alternation. - **Setting the key replaces the default list**, including the `.pnp` entry. - **Symlinked store layouts** put the real files under `node_modules/.pnpm/<name>@<version>/node_modules/<name>/`, so the lookahead has to match `<name>@` (with `/` in a scope written as `+`), as the Jest docs show for that layout. ## Fix 2: let Jest `require()` the ES module Jest 30 can load an ES module from CommonJS the way Node's own `require(esm)` does, without transforming it, on **Node 24.9 or later**. The docs and the error message mention only the Node version, but the feature builds on Node's VM modules API, so Jest must run with `--experimental-vm-modules`, for example `NODE_OPTIONS=--experimental-vm-modules npx jest`. In a run against Jest 30.5.2 on Node 25 the same test failed with the error above without the flag and passed with it. Its limits: - Packages resolve through the `require` and `module-sync` conditions, as in Node. A package exposing its ESM entry only under `import` fails with `ERR_PACKAGE_PATH_NOT_EXPORTED`. - An ES module whose graph uses top-level `await` throws `ERR_REQUIRE_ASYNC_MODULE`; load it with `await import(...)` instead. - `jest.mock` targets CommonJS; mocking an ES module that is required goes through `jest.unstable_mockModule`, which the mocking lesson covers. - On older Node, `require()` of an ES module still fails, so Fix 1 is the portable route. ## Fix 3 and a decoy - **Full native ESM mode**, with `transform: {}` or an ESM-emitting transformer, `--experimental-vm-modules` and `extensionsToTreatAsEsm` for `.ts` or `.jsx`, runs the whole suite as ES modules. Jest still marks this support as experimental. - **The decoy: the environment.** Under `jsdom` the `browser` export condition applies, so a package can resolve to an ESM-only browser build in the web package while the API package, under `node`, loads its CommonJS build. If only the jsdom project fails, look at `testEnvironmentOptions.customExportConditions` before rewriting patterns. ## A diagnosis checklist 1. Read the path in the error: is the failing file your code or a dependency under `node_modules`? 2. Run `jest --showConfig` and check the effective `transform` and `transformIgnorePatterns` of the project that failed. 3. Check whether only one environment fails, which points at export conditions rather than transforms. 4. After changing Babel config or patterns, clear the cache before trusting the result. ## Choosing | Situation | Reach for | |---|---| | A few ESM-only dependencies, any Node version | allowlist in `transformIgnorePatterns` plus a CommonJS-emitting transformer | | Node 24.9+ and no wish to transform dependencies | `--experimental-vm-modules` and `require(esm)` | | Only the jsdom project fails | the `browser` export condition |

  • Why does splitting the allowlist into two transformIgnorePatterns entries skip both packages?
    A file is left untransformed if it matches any pattern. `'/node_modules/(?!foo/)'` matches every path under `node_modules` except foo, including bar, and the second pattern matches foo. Together they cover both, so neither is transformed. Put the packages in one alternation: `'/node_modules/(?!(foo|bar)/)'`.
  • On Node 24.9 or later, when does Jest's require(esm) still fail for a package?
    When the package exposes its ESM entry only under the `import` condition, Node's rules give `ERR_PACKAGE_PATH_NOT_EXPORTED`, because require resolves through `require` and `module-sync`. When the module graph uses top-level `await`, it throws `ERR_REQUIRE_ASYNC_MODULE`. And without `--experimental-vm-modules`, Jest cannot use the feature at all.

  • Jest transforms node_modules by default, so an ESM package must be broken.
  • Listing each package in its own transformIgnorePatterns entry allowlists all of them.
  • Adding '.js' to extensionsToTreatAsEsm makes one dependency load as ESM.
  • On Node 24.9 or later Jest requires ESM natively with no extra flag.
  • testPathIgnorePatterns is what stops Jest compiling files in node_modules.

Assumes Jest 30.5.2: require(esm) on Node 24.9+ arrived in Jest 30.4.0, and 30.5.0 replaced the generic 'Jest encountered an unexpected token' report with this message; Jest 29 has neither.