Issue
I’m running into error SyntaxError: Cannot use import statement outside a module
for my jest unit tests after switching one of the packages in our dependencies. The package is a hard requirement and we cannot do anything with it. After looking into the issue, I believe it’s because the package doesn’t ship a cjs output and Jest couldn’t understand esm syntax.
I’ve seen tons of discussions/solutions for this topic and tried pretty much every solution I could find online. But unfortunately none of them worked for me. I’ve created a repo as a minimal repro of the issue. Here is the link.
What I have tried
- Different presets for ts-jest
- Adding
babel-jest
together with different plugins to deal with the js files in the 3rd party package. Tried different formats of the config (js file, json, .bablerc) - Modifying transform setup in Jest configuration as
'^.+\.jsx?$': 'babel-jest', '^.+\.tsx?$': 'ts-jest'
and all other possibilities around this. - In Jest configuration,
testPathIgnorePatterns
,transformIgnorePatterns
. I thought this would be the solution but it didn’t. Maybe I was not doing it correctly? - Adding
useESM
to ts-jest config - And so on
What I have not tried
The experimental esm support provided by jest, as it’s experimental and doesn’t meet our requirement.
I’d appreciate it if you could play around with the repro repo and give me some suggestions
2
Answers
Since you
allowJS
in to be used in your tsconfigyou can change the
transform
pattern to allow js files as well and add the package to thetransformIgnorePatterns
just try this modification in your package.json
"dependencies": {
//your previous modules
"cross-env": "^7.0.3",
}
"scripts": {
},
mine was working !