首页 文章

使用带有create-react-app的MobX可观察装饰器

提问于
浏览
10

MobX docs告诉我,我必须"use the transform plugin transform-decorators-legacy and make sure it is first in the plugins list",以便装饰工作 . MobX样板项目表明我需要 .babelrc 如下:

{
  "presets": [
    "react",
    "es2015",
    "stage-1"
  ],
  "plugins": ["transform-decorators-legacy", "react-hot-loader/babel"]
}

如何使用create-react-app生成的项目执行此操作?任何尝试使用 @ 装饰器错误 . 即使项目是'ejected',也没有 .babelrc .

5 回答

  • 10

    除非eject,否则不能使用装饰器语法 . 但是,您可以在没有 @ 的情况下使用MobX,因为它只是一种语法糖 .

    丹·阿布拉莫夫has articulated the reason for this

    我们的立场很简单:我们添加足够稳定的变换(如异步/等待)或Facebook大量使用的变换(如类属性) . 只有这样才能让我们有信心建议它们,因为如果标准中的某些内容发生变化,我们将编写并发布一个codemod来迁移它们 . 由于我们目前不使用装饰器,如果标准变得不兼容,我们不会自行提供迁移路径 . 此外,装饰者甚至没有Babel正式支持(-legacy是有原因的) . 当他们配置稍微不正确时,人们会指责React .

    您也可以查看create-react-app-mobx

    相关讨论:

  • 1

    有's an alternative now that was not available at the time of the accepted answer. It' s custom-react-scripts . 它将允许您在CRA应用程序中启用装饰器,SASS和其他细节 . 并且它没有弹出它 .

    有一个很好的medium article解释它背后的想法 .

  • 4

    你可以用https://www.npmjs.com/package/react-app-rewire-mobx

    React App Rewired将为您提供访问配置的权限,而不是您只需设置包 .

    npm install react-app-rewired --save
    
    // create a file named config-overrides.js
    
    /* config-overrides.js */
    
    const rewireMobX = require('react-app-rewire-mobx');
    
    module.exports = function override(config, env) {
      config = rewireMobX(config, env);
      return config;
    }
    

    Note: 这可以避免弹出 . CRA不支持修改config https://github.com/facebookincubator/create-react-app/issues/99#issuecomment-234657710 .

  • 9

    现在,你可以在node_modules / babel-preset-react-app / index.js插件数组中推送 require.resolve('babel-plugin-transform-decorators-legacy')

  • 2

    这是我发现的没有弹出的最佳解决方案 . 替换create-react-scripts .

    https://www.npmjs.com/package/custom-react-scripts

    如果您有一个新项目,请在终端中使用此项目:

    create-react-app my-app --scripts-version custom-react-scripts
    

    然后cd进入my-app目录并创建一个.env文件 . 将.env文件编辑为:

    REACT_APP_BABEL_STAGE_0=true
    REACT_APP_DECORATORS=true
    

    您的应用现在将支持装饰者 .

    如果您有现有应用并想要添加此应用 . 然后像上面那样添加.env:

    npm i custom-react-scripts --save
    

    删除package.json中的react-scripts . 不要将脚本从react-scripts start更改为create-react-scripts start . 保持脚本不变 .

    现在用装饰器添加你的mobx东西,享受更少的样板代码 .

    我最后的package.json

    { "name": "mobx-test", "version": "0.1.0", "private": true, "dependencies": { "custom-react-scripts": "^0.2.1", "mobx": "^3.4.0", "mobx-react": "^4.3.5", "react": "^16.2.0", "react-dom": "^16.2.0" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" } }

    哦,如果你使用vscode,你会想要隐藏有关不支持的装饰器的警告 . 为此,使用此方法将tsconfig.json文件添加到项目中

    { "compilerOptions": { "experimentalDecorators": true, "allowJs": true } }

相关问题