【问题标题】:Is it possible to use decorators with create-react-app?是否可以将装饰器与 create-react-app 一起使用?
【发布时间】:2020-02-03 01:09:57
【问题描述】:

我知道由于 Babel 不支持开箱即用的装饰器(因为它处于定义的早期阶段)create-react-app 也不支持它。

我知道你可以弹出生成的应用程序并配置 Babel 以支持它们,但我不想这样做。

最后,像 MobX 这样的库允许您在不实际使用装饰器的情况下使用装饰器的行为,借助 https://mobx.js.org/best/decorators.html 中描述的一些实用功能

React 有类似的东西吗?

【问题讨论】:

    标签: javascript reactjs create-react-app


    【解决方案1】:

    是的,你可以,但你需要一些东西,

    确保您已安装 react-app-rewiredcustomize-cra,以便您可以覆盖 webpack 和 babel 配置

    安装@babel/plugin-proposal-decorators

    并更新您的config-overrides.js 文件:

    const { override, addBabelPlugin } = require("customize-cra");
    const pluginProposalDecorators = require("@babel/plugin-proposal-decorators");
    
    module.exports = override(  
      addBabelPlugin(pluginProposalDecorators)
    );
    

    【讨论】:

    • 对我来说,这失败了,因为插件要求设置其选项之一。假设您需要设置“decoratorsBeforeExport”或“legacy”(两个布尔选项),还是什么?我不知道。为了其他人对这些工具不熟悉,这就是最终的工作:我用“addBabelPlugin([pluginProposalDecorators, {decoratorsBeforeExport: false}])”替换了 override() 的参数,然后我参考了stackoverflow.com/questions/52628207/… 来学习实际使用插件不会崩溃。
    【解决方案2】:

    还可以通过将 tsconfig.json 文件添加到项目中来使用带有 create-react-app 的装饰器,这意味着启用对 typescript 的支持。

    您需要将 experimentalDecorators 设置为 true in tsconfig.json 的编译器选项

    希望我们知道 .js 和 .tsx 文件可以共存,所以无论我们想要使用装饰器的哪个文件,我们都可以转换为 .tsx 其余文件可以保留 .js 文件

    {
        "compilerOptions": {
            "target": "esnext",
            "lib": ["dom", "dom.iterable", "esnext"],
            "allowJs": true,
            "skipLibCheck": true,
            "esModuleInterop": true,
            "allowSyntheticDefaultImports": true,
            "strict": true,
            "forceConsistentCasingInFileNames": true,
            "module": "esnext",
            "moduleResolution": "node",
            "resolveJsonModule": true,
            "isolatedModules": true,
            "noEmit": true,
            "jsx": "react",
            "noImplicitThis": false, 
            "experimentalDecorators": true,  //<---- 
            "types": ["cypress"]
        },
        "include": ["src"]
    }
    

    【讨论】:

      猜你喜欢
      • 2019-04-12
      • 2019-03-09
      • 2017-09-14
      • 2019-01-30
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 2017-01-08
      • 2017-10-26
      相关资源
      最近更新 更多