问题答案 12026年5月29日 00:29
How to get MobX Decorators to work with Create- React -App v2?
In Create-React-App v2 (abbreviated as CRA v2), using MobX Decorators requires configuring the project to support decorator syntax. CRA does not natively support decorators by default, so we need to modify the configuration files. Generally, there are two approaches: using and , or manually configuring Babel.Using react-app-rewired and customize-craStep 1: Install necessary dependenciesFirst, install and , which enable modifying webpack and Babel configurations without ejecting CRA.Step 2: Modify package.jsonUpdate the scripts section in to use for starting, building, and testing the project.Step 3: Create configuration fileCreate a file in the project root to enable decorator support.This code activates legacy decorator support via .Manually configuring BabelIf you prefer not to use , you can manually eject the CRA configuration.Step 1: Eject configurationThis generates and folders where you can locate the Babel configuration files.Step 2: Modify Babel configurationIn the Babel configuration file (typically in or ), add the decorator plugin:Ensure you have installed this plugin:ConclusionUsing and is the recommended approach for configuring CRA to support decorators, as it avoids ejecting the CRA configuration, simplifying maintenance. However, if the project requires more complex customizations, the eject method remains an alternative. After implementing either method, you can leverage MobX decorators in your CRA project to manage application state.