【问题标题】:How can I enable decorators support when running tests with CRA 2.1?使用 CRA 2.1 运行测试时,如何启用装饰器支持?
【发布时间】:2019-04-05 09:12:18
【问题描述】:

我正在尝试对使用装饰器和 Typescript 与 Create React App v2.1.0 配合使用的 React 应用程序进行测试

我知道装饰器不受官方支持。

感谢React App Rewired@babel/plugin-proposal-decorators,我可以正常运行应用程序。

我卡住的地方是在运行测试时启用装饰器支持。

我的 npm test 脚本是:"test": "react-app-rewired test --env=jsdom --runInBand"

测试失败:

“decorators”插件需要一个“decoratorsBeforeExport”选项, 其值必须是布尔值。如果您从巴比伦/巴别塔迁移 6 或者想使用旧的装饰器建议,你应该使用 'decorators-legacy' 插件而不是 'decorators

我尝试添加一个 .babelrc 文件,其中包含以下内容:

{
  "plugins": [["@babel/plugin-proposal-decorators", { "legacy": true }]]
}

但会被:

不能同时使用 decorators 和 decorators-legacy 插件

【问题讨论】:

  • 在 babelrc 添加这些:[ "@babel/plugin-proposal-decorators", { "legacy": true } ], [ "transform-class-properties", { "loose": true }] 并安装允许您使用装饰器的转换类属性
  • @somsgod 这会导致相同的错误消息

标签: reactjs typescript jestjs create-react-app


【解决方案1】:

? 我是 Create React App 的维护者。

如果您使用 TypeScript 并使用测试,则支持装饰器,无需额外配置(CRA ^2.1.12.1.0 中存在错误)。

装饰器只有 JavaScript 不支持


首先,删除react-app-rewired 并将您的脚本切换回react-scripts。 接下来,删除您的 .babelrc 文件。

最后,使用装饰器将任何文件转换为 TypeScript 文件 (.tsx)。现在应该一切正常!

另外,您的测试脚本应该只读取"test": "react-scripts test""test": "react-scripts test --runInBand"。按照 2.0 升级指南中的规定,传递 --env=jsdom 是不必要的。

【讨论】:

【解决方案2】:

@Onlyann 备份您当前的 package.json 或项目。

试试这个配置,它应该对你有帮助,之后你可以添加额外的包。

// package.json 
    "@babel/core": "^7.0.0-beta.42",
    "@babel/plugin-proposal-class-properties": "^7.0.0-beta.42",
    "@babel/plugin-proposal-decorators": "^7.0.0-beta.42",
    "@babel/plugin-transform-runtime": "^7.0.0-beta.42",
    "@babel/preset-env": "^7.0.0-beta.42",
    "@babel/preset-react": "^7.0.0-beta.42",
    "@babel/preset-stage-2": "^7.0.0-beta.42", 

// .babelrc 
   {
    "presets": [
        ["@babel/preset-env", { "modules": false }],
        "@babel/preset-react",
        "@babel/preset-stage-2"
    ],
    "plugins": [
        "@babel/plugin-transform-runtime",
        "@babel/plugin-proposal-decorators",
        ["@babel/plugin-proposal-class-properties", { "loose": true }]
    ],
    "env": {
        "development": {
            "plugins": ["react-hot-loader/babel"]
        }
    } }

【讨论】:

  • 不。这个问题的关键之一是它使用了 Create React App。您是否尝试过建议的解决方案?
  • 我不使用创建反应应用程序。我已经手动设置了 React + Webpack + Babel + Mobx。您能否分享您的 package.json 和 babel 内容将尝试在我方解决您的问题。
  • 如果不弹出,您目前无法使 cra v2 使用自定义 babel 配置。我希望这会在某个时候改变。
猜你喜欢
  • 2017-08-20
  • 2021-07-21
  • 2015-06-24
  • 2015-03-10
  • 2015-09-02
  • 2017-02-22
  • 2017-07-18
  • 2020-05-19
  • 1970-01-01
相关资源
最近更新 更多