【问题标题】:Jest - Cannot use import statement outside a module - using Rescript开玩笑 - 不能在模块外使用 import 语句 - 使用 Rescript
【发布时间】:2021-03-28 04:56:12
【问题描述】:

我正在尝试在使用 react-scripts 生成的 React 项目中运行单元测试,我在其中添加了 ReScript 支持。

但是,当我运行测试时,我在转译的 javascript 代码中遇到了错误。

错误详情:

/Users/massimilianodacunzo/Projects/Elixir/test-project/apps/phoenix_react_web/assets/node_modules/bs-platform/lib/es6/array.js:3
import * as Curry from "./curry.js";
^^^^^^

SyntaxError: Cannot use import statement outside a module

  1 |
  2 |
> 3 | import * as $$Array from "../../../node_modules/bs-platform/lib/es6/array.js";
    | ^
  4 | import * as React from "react";
  5 |
  6 | function TestComponent(Props) {

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
  at Object.<anonymous> (src/components/users/TestComponent.bs.js:3:1)

我要测试的组件:

App.res

%%raw(`
import logo from './logo.svg';
import './App.css';
`)

@react.component
let make = () => {
    <div className="App">
        <TestComponent elements={["1", "2", "3"]} />
    </div>
}

TempComponent.res

@react.component
let make = (
    ~elements: array<string>
) => {
    <ul>
        {
            React.array(
                elements 
                |> Array.map(e => 
                    <li key={e}>{React.string(e)}</li>)
            )
        }
    </ul>
}

生成的TestComponent.bs.js

import * as $$Array from "../../../node_modules/bs-platform/lib/es6/array.js";
import * as React from "react";

function TestComponent(Props) {
  var elements = Props.elements;
  return React.createElement("ul", undefined, $$Array.map((function (e) {
                    return React.createElement("li", {
                                key: e
                              }, e);
                  }), elements));
}

var make = TestComponent;

export {
  make ,
  
}
/* react Not a pure module */

我可以向react-scripts test 脚本添加任何其他配置吗?

【问题讨论】:

  • 这是您在使用像 create-react-appreact-scripts 这样的生成器时遇到的问题。只有在您冒险走出它为自己建造的小盒子时,它才会很方便,然后您必须支付实际成本,并支付巨额利息。不过,这里可能会有一些帮助:github.com/glennsl/bs-jest/issues/63

标签: reactjs jestjs rescript


【解决方案1】:

根据glennsl的评论,我关注了git问题,发现我的bsconfig.json文件中的配置将package-specs模块指定为es6。如果我将配置更改为 commonjs,则不会出现测试错误。

{
    ...
    "package-specs": {
      "module": "commonjs",
      "in-source": true
    }
    ...
}

再次感谢glennsl 为我指明了正确的方向。

【讨论】:

    猜你喜欢
    • 2023-01-31
    • 2020-12-02
    • 2020-04-29
    • 2020-05-09
    • 2020-02-09
    • 2021-08-14
    • 2020-01-27
    • 2020-02-11
    相关资源
    最近更新 更多