Jest - SyntaxError:不能在模块外使用导入语句 [英] Jest - SyntaxError: Cannot use import statement outside a module
问题描述
我使用的是 jest:24.9.0
,没有任何配置,从 create-react-app 全局安装.在这些文件中,我使用了 es6 模块.使用"test":"react-scripts test"
I am using jest:24.9.0
without any configuration, installed globally from a create-react-app. Inside these files I am using es6 modules. There is no error when using "test": "react-scripts test"
但是,当我将 jest
与 "test": "jest --config jest.config.js" 一起使用时,
我看到以下错误.
However when I move to use jest
with "test": "jest --config jest.config.js",
I see the below error.
FAIL src/configuration/notifications.test.js
● Test suite failed to run
/var/www/management/node/src/configuration/notifications.test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import notifications from './notifications';
^^^^^^
SyntaxError: Cannot use import statement outside a module
推荐答案
Jest 不支持 ES6
模块,因此当您直接使用 Jest 运行测试时会抛出此错误.如果你想这样运行,那么你必须添加 babel.
Jest doesn't support ES6
module and hence throwing this error when you directly run the test with Jest. if you want to run like that then you have to add babel.
另一方面,当您使用 react-scripts
运行测试时,它会在幕后使用 babel 来转换代码.
On the other side, when you run the test with react-scripts
it uses babel behind the scene to Transpile the code.
在较新版本的 jest 中,babel-jest
现在由 Jest 自动加载并完全集成
In newer version of jest,
babel-jest
is now automatically loaded by Jest and fully integrated
希望这能回答您的问题.
Hope this answer your question.
开玩笑地添加 babel.
安装
babel-jest
现在由 Jest 自动加载并完全集成.仅当您使用 babel-jest 转换 TypeScript 文件时才需要此步骤.
babel-jest
is now automatically loaded by Jest and fully integrated. This step is only required if you are using babel-jest to transform TypeScript files.
npm install --save-dev babel-jest
使用
在您的 package.json
文件中进行以下更改:
In your package.json
file make the following changes:
{
"scripts": {
"test": "jest"
},
"jest": {
"transform": {
"^.+\.[t|j]sx?$": "babel-jest"
}
}
}
创建.babelrc
配置文件
Create .babelrc
configuration file
在你的项目根目录中创建一个 babel.config.json
配置并启用一些 presets
.
Create a babel.config.json
config in your project root and enable some presets
.
首先,您可以使用 env 预设,它为 ES2015+ 启用转换
To start, you can use the env preset, which enables transforms for ES2015+
npm install @babel/preset-env --save-dev
为了启用预设,您必须在 babel.config.json
文件中定义它,如下所示:
In order to enable the preset you have to define it in your babel.config.json
file, like this:
{
"presets": ["@babel/preset-env"]
}
这篇关于Jest - SyntaxError:不能在模块外使用导入语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!