antd簡介
antd 是螞蟻金服推出的一套非常好的React UI庫,使用起來特別方便,而且也推出了Antd手機端庫,同時還推出了vue的使用方式
- 如果沒有按需加載,我們如果想要使用一個標簽,比如
Button,需要導入js和css文件,使用起來不是很方便,而且還會造成性能上面的一個下降,先來看一下正常版本的使用
import React from 'react';
import {
Button
} from 'antd';
import "antd/dist/antd.css";
function App() {
return (
<div className="App">
123
<Button>
按鈕
</Button>
</div>
);
}
export default App;
按需加載
在antd的官網上我們看到了,他說需要babel-plugin-import,然后按照他的配置即可

結果發現我的不好使!那么經過不斷搜索和填坑,終於找到了好用的方式,一共有兩種
一. 暴露配置
- 按照需要的依賴
yarn add babel-plugin-import --dev // 安裝
- 在package.json中找到
eject
"scripts": {
"eject": "react-scripts eject"
}
運行命令
npm run eject
注意: 此操作是不可逆的,他會暴露創建react時候的webpack的配置,而且這個命令只能在剛剛使用腳手架創建好項目之后運行(文件的結構不能發生改變的時候才能暴露)
- 修改webpack.config.dev(開發環境)和webpack.config.prod(構建環境)下的 Process JS with Babel.下的那個options為:
options: {
plugins: [
['import',[{ // 導入一個插件
libraryName: 'antd', // 暴露的庫名
style: true // 直接將ants樣式文件動態編譯成行內樣式插入,就不需要每次都導入
}]]
],
cacheDirectory: true,
},
和
options: {
plugins: [
['import',[{ // 導入一個插件
libraryName: 'antd', // 暴露的庫名
style: true // 直接將ants樣式文件動態編譯成行內樣式插入,就不需要每次都導入
}]]
],
compact: true,
},
- 重新運行一下項目,就可以直接引入組件了
import { Button } from 'antd';
這種方式必須暴露配置,這回讓我們開發的時候不是很方便,所以推薦下面的這種方式
二. (推薦)使用react-app-rewired
- 安裝依賴
npm i react-app-rewired@2.0.2-next.0 babel-plugin-import customize-cra
這個時候就會有一個比較大的坑,react-app-rewired必須制定版本,否則報錯
- 修改啟動方式,在package.json中
原版
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
修改后的版本
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
},
- 在項目的根目錄下創建
config-overrides.js
const {
override,
fixBabelImports,
addLessLoader,
} = require("customize-cra");
module.exports = override(
fixBabelImports("import", {
libraryName: "antd", libraryDirectory: "es", style: true // change importing css to less
}),
addLessLoader({
javascriptEnabled: true,
modifyVars: { "@primary-color": "#1DA57A" }
})
);
- 重新啟動項目,就可以按需加載了
import { Button } from 'antd';
總結
使用
react-app-rewired來代替react-scripts的啟動方式,並且安裝所需要的依賴,在根目錄創建config-overrides.js文件,導入配置即可完成
如果還有問題,可以看我的Demo合集
