I've been struggling to resolve the annoying
SyntaxError: Cannot use import statement outside a module
issue in my React, Typescript, Webpack project. Despite going through numerous Stack Overflow and GitHub threads, I still haven't found a clear solution. Has anyone successfully tackled this problem?
My specific scenario involves testing a module using Jest, but for some reason, Jest is failing to transform the module into plain JavaScript.
The error message I keep encountering is as follows:
/Users/me/dev/Project/project/node_modules/variables/src/variables.js:12
import './main.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
17 |
18 | */
> 19 | import { GlobalVars } from 'variables'
| ^
20 |
21 | export const Vars = new GlobalVars()
22 |
Attempts made to troubleshoot (without success):
Utilizing the
env
setup inbabel.config
:env.test.preset: ['@babel/plugin-transform-modules-commonjs']
Modifying the
transform
settings in Jest configuration such as
and exploring other possible configurations.'^.+\\.jsx?$': 'babel-jest', '^.+\\.tsx?$': 'ts-jest'
Editing the
testPathIgnorePatterns
andtransformIgnorePatterns
in Jest configuration.Switching from
.babelrc.js
to.babel.config.js
...and more.
Current setup details:
package.json
"jest": {
"preset": "ts-jest",
"testEnvironment": "node"
}
.babelrc.js
module.exports = {
presets: [
['@babel/preset-env', { targets: { node: 'current' } }],
'@babel/preset-react',
'@babel/preset-typescript',
],
plugins: [
'@babel/plugin-transform-runtime',
'@babel/proposal-class-properties',
'@babel/transform-regenerator',
'@babel/plugin-transform-template-literals',
'react-hot-loader/babel',
],
}
variables.ts
import { GlobalVars } from 'variables'
export const Vars = new GlobalVars()
variables.spec.ts
import { Vars } from './variables.ts'
describe('Test The Package', () => {
it('Should accept new variables', () => {
Vars.newVariable = 'new variable'
expect(Vars.newVariable).toEqual('new variable')
})
})
Any insights on how to overcome this challenge would be greatly appreciated.