I'm using jest to run some tests on a lib and I've been getting the error "Cannot use import statement outside a module" after I upgraded a lib that now exports to es6, before the upgrade the tests worked just fine.
A screenshot of the error:

The jest.config.js file that I'm using:
module.exports = {
roots: ['<rootDir>/src/'],
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.ts?$',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
};
The tsconfig.json file:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"lib": ["es6", "dom"],
"types": ["jest"],
"sourceMap": true,
"jsx": "react",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"moduleResolution": "node",
"forceConsistentCasingInFileNames": true,
"strict": true,
"emitDecoratorMetadata": true,
"importHelpers": true,
"noEmitHelpers": true,
"noFallthroughCasesInSwitch": true,
"strictFunctionTypes": false,
"pretty": true,
"removeComments": false,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": true,
"experimentalDecorators": true,
"baseUrl": "./"
}
}
And lastly, the babel.config.js file:
module.exports = {
presets: [
[
'@babel/preset-env',
{
targets: {
ie: '11',
},
},
],
'@babel/typescript',
],
plugins: [
['@babel/plugin-proposal-class-properties', { loose: true }],
'@babel/plugin-proposal-object-rest-spread',
'@babel/plugin-transform-object-assign',
'@babel/plugin-transform-runtime',
],
env: {
development: {},
production: {
plugins: ['transform-dev-warning'],
ignore: ['**/test/'],
},
test: {
sourceMaps: 'both',
},
},
};
I've tried pretty much every solution that I could find online but nothing seems to work. If anybody could help me that would be great, thanks in advance!
This is very common issue by using (import) an esm js style that causes the issue. In this case the package is sip.js.
The solution is also very common as well which we just simply configure jest to transform that package by using magic option transformIgnorePatterns. Plus, also tell tsc to compile that esm package too.
In short, here are the thing you would do:
jest.config.js
module.exports = {
// ...
transform: {
'^.+\\(t|j)sx?$': 'ts-jest', // transpile both `ts` + `js` files
},
transformIgnorePatterns: [`/node_modules/(?!(sip\.js))`] // Keep `sip.js` to get transpiled as well
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With