Jest won't transform the module - SyntaxError: Cannot use import statement outside a module
Even though I have tried them separately, I haven't tried them together (transform
and transformIgnorePatterns
). So this jest configuration solved my issue:
"jest": { "preset": "ts-jest", "testEnvironment": "node", "transform": { "node_modules/variables/.+\\.(j|t)sx?$": "ts-jest" }, "transformIgnorePatterns": [ "node_modules/(?!variables/.*)" ] },
My mistakes were:
- Not using
transform
andtransformIgnorePatterns
together. - And defining
babel-jest
as the transformer instead ofts-jest
(I guess that is a problem when the preset of jest is defined asts-jest
. Because if I change it to bebabel-jest
it throws the same error again.):
--- "node_modules/variables/.+\\.(j|t)sx?$": "babel-jest"+++ "node_modules/variables/.+\\.(j|t)sx?$": "ts-jest"
Since jest is not working with esmodules well, you need to add these configurations in jest.config.js to tell Jest to use commonJS builds instead
moduleNameMapper : { '^variables$': 'variables/dist/cjs', '^[NAME OF MODULE YOU WANT TO IMPORT]$': '[NAME OF MODULE YOU WANT TO IMPORT]/dist/cjs'}
I got stuck in the same situation. Due to I had a private untranspiled package which is based on TypeScript, and all my source files and test files were all applied with ECMA ( import syntax ), I encountered the following error as well.
SyntaxError: Cannot use import statement outside a module
The solutions I have tried.
- The above answers, such as use transform, transformIgnorePatterns, moduleNameMapper in
jest.config.ts
. - Followed JEST official document, Configuration Jest#transformignorepatterns-arraystring, I used exactly the same method and even referred to the use case from React Native Guide.
- Removed all
node_modules
, including cache, and reinstalled them. - Used react-scripts and downgrade jest and babel-jest to 26 from 27. There was another issue that occurred.
After all, I found ECMAScript Modules from the JEST official document, the four steps perfectly solved my problem. I pasted their instructions here, however, you should take a look at the document itself.
- Ensure you either disable code transforms by passing transform: {} or otherwise configure your transformer to emit ESM rather than the default CommonJS (CJS).
- Execute node with --experimental-vm-modules, e.g. node --experimental-vm-modules node_modules/.bin/jest or NODE_OPTIONS=--experimental-vm-modules npx jest etc.. On Windows, you can use cross-env to be able to set environment variables.
- Beyond that, we attempt to follow node's logic for activating "ESM mode" (such as looking at type in package.json or mjs files), see their docs for details.
- If you want to treat other file extensions (such as ts) as ESM, please use the extensionsToTreatAsEsm option.