在使用react項目中,不可避免的要使用螞蟻金服出品的ant-desgin前端UI組件,ant-desgin推薦使用 craco (一個對 create-react-app 進行自定義配置的社區解決方案),對 create-react-app 的默認配置進行自定義。
如果在項目中使用mobx進行數據狀態管理,必然要對項目進行配置。因爲mobx中大量使用了ES.net的裝飾語法,但是裝飾語法器語法目前還處於試驗階段,create-react-app默認是不支持的。
之前ant-desginUI文旦推薦使用 react-scripts-rewired 和 customize-cra ,來自定義 create-react-app 的 webpack 配置,如果使用react-scripts-rewired 進行配置的話,結局方案是:
1、首先下載依賴
npm install --save customize-cra
npm install --save react-app-rewired
npm install --save @babel/plugin-proposal-decorators
2.在根目錄創建項目config-overrides.js
const { override, addDecoratorsLegacy } = require('customize-cra');
module.exports = override(
addDecoratorsLegacy()
);
3.修改package.json 啓動配置
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
},
然後重新 npm start 一下就可以了。 but 這邊有一個瑕疵的地方就是
修飾器放在export default 還是報之前的錯;
@testable //修飾器
export default class Two extends Component {
constructor(props) {
super(props);
this.state = {};
}
}
如果我換成下方的寫法。修飾器 放在 class之前就沒錯了。
export default @testable class Two extends Component {
constructor(props) {
super(props);
this.state = {};
}
}
那麼如何在craco 中配置mobx呢?
1、下載依賴
npm install --save @craco/craco
npm install --save @babel/plugin-proposal-decorators
2、在項目根目錄創建一個 craco.config.js
用於修改默認配置
module.exports = {
babel: {
plugins: [
["@babel/plugin-proposal-decorators", { legacy: true }]
]
}
};
3.修改package.json 啓動配置
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
}
然後重新 npm start 一下就可以了。
如果解決的了您的問題請點個贊!