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.
SyntaxError: Cannot use import statement outside a module
# or
Jest encountered an unexpected token ...
To enable ESM support, run node with --experimental-vm-modulesCommon 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 script
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
# or in CI:
NODE_OPTIONS=--experimental-vm-modules npx jestOr transform ESM to CJS
- Configure
transform(babel-jest/ts-jest) to compile ESM/TS down to CommonJS for Jest. - Add ESM-only deps to
transformIgnorePatternsexceptions so they get transformed. - Pick one approach - native ESM (flag) or transform - not both.
How to prevent it
- Set
NODE_OPTIONS=--experimental-vm-modulesfor ESM Jest runs. - Or standardize on a CJS transform for tests.
- Keep the test module strategy consistent across the repo.