相关疑难解决方法(0)

如何在玩笑中解决“无法在模块外使用导入语句”

我有一个使用 TypeScript、Jest、Webpack 和 Babel 构建的 React 应用程序(不使用 Create React App)。尝试运行“yarn jest”时,出现以下错误:

开玩笑的错误

我尝试删除所有软件包并重新添加它们。它没有解决这个问题。我看过类似的问题和文档,但仍然误解了一些东西。我什至按照另一个指南从头开始设置这个环境,但我的代码仍然收到这个问题。

依赖包括...

"dependencies": {
        "@babel/plugin-transform-runtime": "^7.6.2",
        "@babel/polyfill": "^7.6.0",
        "babel-jest": "^24.9.0",
        "react": "^16.8.6",
        "react-dom": "^16.8.6",
        "react-test-renderer": "^16.11.0",
        "source-map-loader": "^0.2.4"
    },
    "devDependencies": {
        "@babel/core": "^7.6.0",
        "@babel/preset-env": "^7.6.0",
        "@babel/preset-react": "^7.0.0",
        "@types/enzyme": "^3.9.2",
        "@types/enzyme-adapter-react-16": "^1.0.5",
        "@types/jest": "^24.0.13",
Run Code Online (Sandbox Code Playgroud)

组件的导入行...

import * as React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import HomePage from "./components/pages";
import {
    Footer,
    Header,
    Navigation,
} from "./components/shared";
Run Code Online (Sandbox Code Playgroud)

测试文件....

import * as React from "react"; …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs babeljs babel-jest ts-jest

80
推荐指数
9
解决办法
7万
查看次数

Jest 不会转换模块 - SyntaxError: 不能在模块外使用 import 语句

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 | 
Run Code Online (Sandbox Code Playgroud)

我试图解决这个问题(但没有奏效):

  • 使用env设置babel.configenv.test.preset: ['@babel/plugin-transform-modules-commonjs']

  • 修改transformJest 配置中的设置'^.+\\.jsx?$': 'babel-jest', '^.+\\.tsx?$': …

typescript jestjs babel-jest ts-jest

40
推荐指数
7
解决办法
4万
查看次数

Jest - SyntaxError: 不能在模块外使用 import 语句

我在jest:24.9.0没有任何配置的情况下使用,从 create-react-app 全局安装。在这些文件中,我使用了 es6 模块。使用时没有错误"test": "react-scripts test"

但是,当我开始使用jestwith 时,"test": "jest --config jest.config.js",我看到以下错误。

 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
Run Code Online (Sandbox Code Playgroud)

javascript reactjs jestjs create-react-app

13
推荐指数
2
解决办法
4432
查看次数