无论我尝试了什么,我都无法摆脱这个错误:SyntaxError: Cannot use import statement outside a module
,真是令人沮丧。这里有没有人解决了这个问题?我已经阅读了数百篇的stackoverflow和github帖子,但没有明确的解决方案。
这是一个React、Typescript、Webpack项目。我正在尝试测试一个模块,但是Jest不知何故无法将模块转换为纯JavaScript。
我收到的错误消息是:
/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 |
我尝试过但无法解决的方法:
在
babel.config
中使用env
的设置:env.test.preset: ['@babel/plugin-transform-modules-commonjs']
修改 Jest 配置中的
transform
设置为'^.+\\.jsx?$': 'babel-jest','^.+\\.tsx?$': 'ts-jest'
,以及其他所有可能性。Jest 配置中的
testPathIgnorePatterns
、transformIgnorePatterns
。使用
.babel.config.js
而不是.babelrc.js
。
...等等。
我的配置如下:
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',
],
}
变量.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')
})
})
有解决这个问题的想法吗?
--experimental-vm-modules
在 Node 中运行实验性 ESM,就像这个答案中所示:https://stackoverflow.com/a/70200697/5078874 - Adrian Escutia Soto