将 MobX 可观察装饰器与 create-react-app 一起使用

Using MobX observable decorators with create-react-app

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

除非你 eject,否则你不能使用装饰器语法。然而,你可以在没有 @ 的情况下使用 MobX,因为它只是一个语法糖。

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

Our position is simple: we add transforms that are either stable enough (like async/await) or heavily used by Facebook (like class properties). Only that lets us be confident in suggesting them, because if something changes in the standard, we’ll write and release a codemod to migrate away from them.

Since we don’t currently use decorators, we don’t take it upon ourselves to provide a migration path if the standard becomes incompatible. Additionally decorators aren’t even officially supported by Babel (-legacy is there for a reason). And when they are configured slightly incorrectly people blame React.

您可能还想查看 create-react-app-mobx

相关讨论:

现在有一个在接受答案时不可用的替代方案。是custom-react-scripts。它可以让您在 CRA 应用程序中启用装饰器、SASS 和其他细节。而且它不会弹出。

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

您可以使用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;
}

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

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

这是我在不弹出的情况下找到的最佳解决方案。替换 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 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 } }