使用create-react-app創(chuàng)建好項(xiàng)目后
yarn add antd
第一種方法 babel-plugin-import
npm run eject
此時(shí)會(huì)提示,該命令不可逆,是否繼續(xù),輸入y,這樣所有配置項(xiàng)就都出來了。這時(shí)候也可以做一些定制化的配置了
然后 安裝babel-plugin-import
yarn add babel-plugin-import
打開.babelrc,添加
{
"plugins": [
["import", {
"libraryName": "antd",
"libraryDirectory": "es",
"style": "css" // `style: true` 會(huì)加載 less 文件
}]
]
}
這種方法會(huì)暴露所有的配置文件,操作需要謹(jǐn)慎,可以用下面這種方法
第二種方法 react-app-rewired
引入 react-app-rewired 并修改 package.json 里的啟動(dòng)配置。
yarn add react-app-rewired customize-cra
&1 修改package.json
/* package.json */
"scripts": {
- "start": "react-scripts start",
+ "start": "react-app-rewired start",
- "build": "react-scripts build",
+ "build": "react-app-rewired build",
- "test": "react-scripts test",
+ "test": "react-app-rewired test",
}
&2 然后在項(xiàng)目根目錄創(chuàng)建一個(gè) config-overrides.js 用于修改默認(rèn)配置。
module.exports = function override(config, env) {
// do stuff with the webpack config...
return config;
};
此時(shí)就實(shí)現(xiàn)按需加載了,
然后只需從 antd 引入模塊即可,無需單獨(dú)引入樣式。
import { DatePicker } from 'antd';
如果想使用babel-plugin-import又不想npm run eject暴露所有配置文件,可以同時(shí)安裝babel-plugin-import和react-app-rewired,然后執(zhí)行上面的&1&2方法,并修改 *config-overrides.js內(nèi)容為
+ const { override, fixBabelImports } = require('customize-cra');
- module.exports = function override(config, env) {
- // do stuff with the webpack config...
- return config;
- };
+ module.exports = override(
+ fixBabelImports('import', {
+ libraryName: 'antd',
+ libraryDirectory: 'es',
+ style: 'css',
+ }),
+ );
最后重啟 yarn start