乐闻世界logo
搜索文章和话题

How to get MobX Decorators to work with Create- React -App v2?

1个答案

1

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 react-app-rewired and customize-cra, or manually configuring Babel.

Using react-app-rewired and customize-cra

Step 1: Install necessary dependencies

First, install react-app-rewired and customize-cra, which enable modifying webpack and Babel configurations without ejecting CRA.

bash
npm install react-app-rewired customize-cra --save-dev

Step 2: Modify package.json

Update the scripts section in package.json to use react-app-rewired for starting, building, and testing the project.

json
{ "scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-scripts eject" } }

Step 3: Create configuration file

Create a config-overrides.js file in the project root to enable decorator support.

javascript
const { override, addDecoratorsLegacy } = require('customize-cra'); module.exports = override( addDecoratorsLegacy() );

This code activates legacy decorator support via addDecoratorsLegacy.

Manually configuring Babel

If you prefer not to use react-app-rewired, you can manually eject the CRA configuration.

Step 1: Eject configuration

bash
npm run eject

This generates config and scripts folders where you can locate the Babel configuration files.

Step 2: Modify Babel configuration

In the Babel configuration file (typically in package.json or babel.config.js), add the decorator plugin:

json
{ "plugins": [ ["@babel/plugin-proposal-decorators", { "legacy": true }] ] }

Ensure you have installed this plugin:

bash
npm install @babel/plugin-proposal-decorators --save-dev

Conclusion

Using react-app-rewired and customize-cra 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.

2024年8月16日 00:13 回复

你的答案