Jest "SyntaxError: Cannot use import statement outside a module"
Jest hit raw ESM import syntax it did not transform to CommonJS. Usually a dependency ships ESM-only and Jest’s default transformIgnorePatterns skips node_modules, so it is never compiled.
What this error means
A test fails to parse with "SyntaxError: Cannot use import statement outside a module," pointing at a file inside node_modules (an ESM-only package) or at your own untransformed source.
Details:
/app/node_modules/nanoid/index.js:1
({"Object.<anonymous>":function(...){export { nanoid } from './...';
^^^^^^
SyntaxError: Cannot use import statement outside a moduleCommon causes
ESM-only dependency not transformed
Jest ignores node_modules by default. An ESM-only package (e.g. nanoid, uuid v9) is loaded as-is, and its import syntax breaks under CommonJS.
No transform configured for your syntax
Without babel-jest/ts-jest set up, Jest cannot compile your own import/TSX either, producing the same SyntaxError on source files.
How to fix it
Allow-list the ESM package for transform
Carve the ESM dependency out of transformIgnorePatterns so Jest compiles it.
// jest.config.js
module.exports = {
transformIgnorePatterns: ['/node_modules/(?!(nanoid|uuid)/)'],
};Configure a transform for your code
- Add
babel-jestwith@babel/preset-env(andpreset-typescript/preset-reactas needed). - Or use
ts-jestfor TypeScript projects. - Confirm the
transformglob covers your source extensions.
How to prevent it
- Keep
transformIgnorePatternsupdated as ESM-only deps are added. - Standardize on
babel-jestorts-jestfor your stack. - Consider Vitest for projects that are ESM-first.