How to get MobX Decorators to work with Create-React-App v2?
Firstly, install dependencies:
yarn add react-app-rewired customize-cra @babel/plugin-proposal-decorators
Secondly, create config-overrides.js
in root directory with following contents:
const { addDecoratorsLegacy, override, disableEsLint} = require("customize-cra");module.exports = { webpack: override( addDecoratorsLegacy(), disableEsLint() )};
You should be able to use mobx + decorators now.
If you don't have mobx installed already, please run:yarn add mobx mobx-react
.Now you can use decorators.
I had same issue and ended up with using mobx4 where Decorators can be used without decorator syntax.
class Store { //... @action empty() { this.data = [] } @action add(e) { this.data.push(e) }}
can be rewritten as
class Store { //... empty() { this.data = [] } add(e) { this.data.push(e) } }decorate(Store, { add: action, empty: action})
You can use this feature out of the box from CRA2 and do not need to worry about transform decoracy plugin. Thanks Michel Weststrate for this stuff
https://medium.com/@mweststrate/mobx-4-better-simpler-faster-smaller-c1fbc08008da
Option 1: Using decorators with CRA v2
If you refer to Mobx documentation, you can get Mobx decorators to work with CRAv2 by using Typescript:
Decorators are only supported out of the box when using TypeScript in create-react-app@^2.1.1.
However, in some cases, you might still face issues when using Mobx with other react frameworks. In that case:
Option 2: Don't use decorators
A detailed step by step guide is documented here.
If you previously defined your observer react component as:
@observerexport default class MyComponent extends React.Component
Change it to:
const MyComponent = observer(class MyComponent extends React.Component{ /* ... */});export default MyComponent;
If you previously had:
@observable myElement = null;
You need to change it to:
myElement;
then:
decorate(MyComponent, { myElement: observable,})
Hope this helps!