React Antd 按需加載

使用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-importreact-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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容