开玩笑-SyntaxError:无法在模块外部使用import语句 [英] Jest - SyntaxError: Cannot use import statement outside a module

查看:1205
本文介绍了开玩笑-SyntaxError:无法在模块外部使用import语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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.

另一方面, n您使用反应脚本运行测试,它将在后台使用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

希望此问题回答您。

在开玩笑中添加通天塔。

安装

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配置文件

在项目根目录中创建一个 babel.config.json 配置并启用一些预设

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"]
}

检查更多 Babel官方网站

这篇关于开玩笑-SyntaxError:无法在模块外部使用import语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆