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 回答
除非eject,否则不能使用装饰器语法 . 但是,您可以在没有
@
的情况下使用MobX,因为它只是一种语法糖 .丹·阿布拉莫夫has articulated the reason for this
您也可以查看create-react-app-mobx
相关讨论:
https://github.com/facebookincubator/create-react-app/issues/214
https://github.com/mobxjs/mobx/issues/521
https://github.com/facebookincubator/create-react-app/issues/411
有's an alternative now that was not available at the time of the accepted answer. It' s custom-react-scripts . 它将允许您在CRA应用程序中启用装饰器,SASS和其他细节 . 并且它没有弹出它 .
有一个很好的medium article解释它背后的想法 .
你可以用https://www.npmjs.com/package/react-app-rewire-mobx
React App Rewired将为您提供访问配置的权限,而不是您只需设置包 .
Note: 这可以避免弹出 . CRA不支持修改config https://github.com/facebookincubator/create-react-app/issues/99#issuecomment-234657710 .
现在,你可以在node_modules / babel-preset-react-app / index.js插件数组中推送
require.resolve('babel-plugin-transform-decorators-legacy')
这是我发现的没有弹出的最佳解决方案 . 替换create-react-scripts .
https://www.npmjs.com/package/custom-react-scripts
如果您有一个新项目,请在终端中使用此项目:
然后cd进入my-app目录并创建一个.env文件 . 将.env文件编辑为:
您的应用现在将支持装饰者 .
如果您有现有应用并想要添加此应用 . 然后像上面那样添加.env:
删除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 } }