Skip to content
Latchkey

Jest "SyntaxError: Cannot use import" - Fix --experimental-vm-modules in CI

Jest’s native ESM support is gated behind Node’s --experimental-vm-modules flag. Without it, Jest loads ESM test files through its CommonJS path and they fail to parse import syntax.

What this error means

Jest tests using import (or testing ESM-only packages) fail with a SyntaxError about import, or Jest warns that ESM support needs the experimental flag. The same tests pass once the flag is set.

Jest output
SyntaxError: Cannot use import statement outside a module
# or
Jest encountered an unexpected token ...
To enable ESM support, run node with --experimental-vm-modules

Common causes

Jest run without the ESM flag

Native ESM in Jest requires Node’s --experimental-vm-modules. Without it, Jest cannot evaluate ES modules and import syntax fails.

ESM-only dependencies under test

Even with mostly-CJS tests, importing an ESM-only package pulls in the ESM path, which needs the flag.

How to fix it

Pass the flag via NODE_OPTIONS

Enable Node’s experimental VM modules when invoking Jest.

package.json / Terminal
# package.json script
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
# or in CI:
NODE_OPTIONS=--experimental-vm-modules npx jest

Or transform ESM to CJS

  1. Configure transform (babel-jest/ts-jest) to compile ESM/TS down to CommonJS for Jest.
  2. Add ESM-only deps to transformIgnorePatterns exceptions so they get transformed.
  3. Pick one approach - native ESM (flag) or transform - not both.

How to prevent it

  • Set NODE_OPTIONS=--experimental-vm-modules for ESM Jest runs.
  • Or standardize on a CJS transform for tests.
  • Keep the test module strategy consistent across the repo.

Related guides

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