jest cannot use import statement outside a module
Fixes Jest ESM 'cannot use import statement' errors in test files. Use when your own test files use import and Jest rejects them. Not for node_modules ESM (separate skill).
TL;DR
Jest runs in CommonJS by default, so import in your test files fails without a transform. Configure babel-jest or ts-jest to transform your sources, or run Jest in ESM mode deliberately.
Error
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCodeSteps
- Check for a babel config that handles ESM-to-CJS. Expected:
@babel/preset-envpresent, or the error explains its absence. - If using TypeScript, ensure ts-jest or babel-jest with preset-typescript processes the test files. Expected:
.tstests transform. - Verify
transformin jest config covers your file extensions. Expected: no gaps for.ts,.tsx,.jsx. - As an alternative, run Jest as ESM (
NODE_OPTIONS=--experimental-vm-modules), but only if the whole toolchain is ESM-ready. Expected: a deliberate choice, not an accident. - Re-run. Expected: imports work.
When to use
- The error names your own test or source file.
- A fresh Jest setup or a TS migration.
When not to use
- The error names a file in node_modules (transformIgnorePatterns skill).
- You are on Vitest (native ESM; different setup).
Tool compatibility
- Jest 27 through 30; babel-jest, ts-jest.
Variant phrasings
Jest SyntaxError import statement
The short form; transform configuration is the fix.
Cannot use import statement in Jest with TypeScript
ts-jest or babel typescript preset missing.
Why it happens
Node-style ESM import is not valid CommonJS. Jest's default runtime is CJS, so something must compile the syntax away.
Edge cases
- Mixed CJS/ESM codebases need per-file transform decisions; keep the config explicit.
jest.mock()hoisting interacts with ESM transforms; keep mocks at the top.- ESM mode in Jest is still rough; CJS transform remains the pragmatic default.
Provenance
Resolved from the public thread: https://vectle.com/posts/pst_gePA4FfDGi09hiYIANu9TA
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.