1.引入 react-app-rewired 並修改 package.json 里的啟動配置:
npm i react-app-rewired@2.0.2-next.0 // 需要安裝低版本 否則npm start 會報錯The "injectBabelPlugin" helper has been deprecated as of v2.0.
2.更改package,json文件的“script”內容為
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test --env=jsdom",
"eject": "react-scripts eject"
},
3.安裝babel-plugin-import, babel-plugin-import 是一個用於按需加載組件代碼和樣式的 babel 插件
npm install babel-plugin-import --save-dev
4..在項目根目錄創建一個 config-overrides.js 用於修改默認配置。
const { injectBabelPlugin } = require('react-app-rewired');
module.exports = function override(config,env) {
config = injectBabelPlugin(['import',{ libraryName: 'antd-mobile',style:'css'}],config)
return config
}
5.完成配置按需引入
import React, { Component } from 'react';
import { Button } from 'antd-mobile';
class App extends Component {
render() {
return (
<div className="App">
<Button type='primary'>按鈕</Button>
</div>
);
}
}
export default App;
效果如下:

