目前尚未启用对实验语法'decorators-legacy'的支持
我尝试在decorators-legacy
添加@babel/plugin-proposal-decorators
babel插件和{ legacy: true }
与.babelrc
但没有效果。
有人设法使MobX装饰器与CRA2一起工作吗?
我有同样的问题,最终使用mobx4,其中装饰器可以使用没有装饰器语法。
class Store {
//...
@action empty() {
this.data = []
}
@action add(e) {
this.data.push(e)
}
}
可以改写为
class Store {
//...
empty() {
this.data = []
}
add(e) {
this.data.push(e)
}
}
decorate(Store, {
add: action,
empty: action
})
您可以使用CRA2开箱即用的此功能,而无需担心转换decoracy插件。感谢Michel Weststrate这个东西
https://medium.com/@mweststrate/mobx-4-better-simpler-faster-smaller-c1fbc08008da
我做了一个与Babel 7和Mobx(装饰工作)的React App 2.0的example project,没有弹出! :
我用来创建这个项目的链接:
https://github.com/timarney/react-app-rewired/issues/348
https://github.com/arackaf/customize-cra#addbabelpluginsplugins
https://www.leighhalliday.com/mobx-create-react-app-without-ejecting
首先,安装依赖项:
yarn add react-app-rewired customize-cra @babel/plugin-proposal-decorators
其次,在根目录中创建config-overrides.js
,内容如下:
const {
addDecoratorsLegacy,
override,
disableEsLint
} = require("customize-cra");
module.exports = {
webpack: override(
addDecoratorsLegacy(),
disableEsLint()
)
};
你现在应该可以使用mobx +装饰器了。
如果您还没有安装mobx,请运行:yarn add mobx mobx-react
。现在你可以使用装饰器了。
使用CRA2时,为了使用MOBX5,您必须执行以下操作。
npm install -save mobx mobx-react
现在在商店文件中添加以下行。
import {decorate, observable} from "mobx"
import {observer} from "mobx-react"
现在你可以使用这样的东西了。
class Store {
//...
}
decorate(Store, {
list: observable
})
const appStore = new Store()`
虽然如果你想避免使用样板代码,其他答案是正确的,可以在CRA2中使用装饰器,而不使用https://github.com/timarney/react-app-rewired/和https://github.com/arackaf/customize-cra弹出
你应该这样做,如果你使用babel7你必须在babelrc中添加一些配置安装支持装饰器:npm i --save-dev @ babel / plugin-proposal-class-properties @ babel / plugin-proposal-decorators。并在.babelrc文件中启用它:
"plugins": [
["@babel/plugin-proposal-decorators", { "legacy": true}],
["@babel/plugin-proposal-class-properties", { "loose": true}]
]
}
或者您可以使用MobX内置实用程序,如:
import { observable, computed, action, decorate } from "mobx";
class Timer {
start = Date.now();
current = Date.now();
get elapsedTime() {
return this.current - this.start + "milliseconds";
}
tick() {
this.current = Date.now();
}
}
decorate(Timer, {
start: observable,
current: observable,
elapsedTime: computed,
tick: action
});
我有同样的问题,我使用了mobx-utility,每件事都完全适合我
选项1:使用带CRA v2的装饰器
如果你引用Mobx documentation,你可以使用Typescript让Mobx装饰器与CRAv2一起使用:
在create-react-app@^2.1.1中使用TypeScript时,仅支持装饰器开箱即用。
但是,在某些情况下,将Mobx与其他反应框架一起使用时可能仍会遇到问题。在这种情况下:
选项2:不要使用装饰器
here记录了详细的分步指南。
如果您之前将观察者反应组件定义为:
@observer
export default class MyComponent extends React.Component
将其更改为:
const MyComponent = observer(class MyComponent extends React.Component{
/* ... */
});
export default MyComponent;
如果你以前有:
@observable myElement = null;
您需要将其更改为:
myElement;
然后:
decorate(MyComponent, {
myElement: observable,
})
希望这可以帮助!
npm run eject
在第162行附近将粗线添加到/config/webpack.config.dev.js。确保在/config/webpack.config.prod.js上执行相同的操作,否则应用程序将无法构建
插件:[“@ babel / plugin-proposal-decorators”,{“legacy”:true}],