create-react-app:是一個建立react項目特別方便的腳手架,他幫咱們配置好了各類須要使用的工具,減小了不少工做量。antd:是螞蟻金服推出的一個很優秀的react UI庫,其中包含了不少咱們常常使用的組件,對於小白學習react來講十分友好!css
當咱們沒有進行任何配置直接在這個項目中使用antd庫時,會在控制檯看到以下提示:react
那麼就有多是使用了 import { Button } from 'antd';
的寫法引入了 antd 下全部的模塊,這會影響應用的網絡性能,這時就體現了按需加載的重要性!webpack
import Button from 'antd/lib/button'; // 須要結構賦值的方式引入 import 'antd/lib/button/style'; // 或者 antd/lib/button/style/css 加載 css 文件
這個方法的優勢是比較簡單,不需再次配置,直接加載便可,可是比較麻煩,每次載入一個新的組件都須要先載入組件,在加載組件的css文件,代碼冗餘。git
yarn add babel-plugin-import --dev // 安裝
關於插件的介紹和使用,可參考:https://blog.csdn.net/qq_3580...github
使用這個插件以後仍然能夠用:import { Button } from 'antd';
來引入組件,可是這個時候插件會幫你轉換成 antd/lib/xxx 的寫法。另外此插件配合 style 屬性能夠作到模塊樣式的按需自動加載。這個時候問題來了,經過create-react-app來建立的react項目的webpack是封裝後的,在項目中是隱藏的,如何修改其配置呢?web
下面介紹兩種比較經常使用的方法:json
"scripts": { "eject": "react-scripts eject" }
在執行完yarn eject以後,會將項目中全部的配置項反編譯出來,就能夠認開發者任意修改配置項,可是這個過程是不可逆的,一旦執行,就不能恢復,不再能經過升級其中的react-scripts包來升級create-react-app的特性。
options: { plugins: [ ['import',[{ // 導入一個插件 libraryName: 'antd', // 暴露的庫名 style: true // 直接將ants樣式文件動態編譯成行內樣式插入,就不須要每次都導入 }]] ], cacheDirectory: true, },
和babel
options: { plugins: [ ['import',[{ // 導入一個插件 libraryName: 'antd', // 暴露的庫名 style: true // 直接將ants樣式文件動態編譯成行內樣式插入,就不須要每次都導入 }]] ], compact: true, },
import { Button } from 'antd';
yarn add react-app-rewired --dev
/* 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 --env=jsdom", + "test": "react-app-rewired test --env=jsdom", }
const {injectBabelPlugin} = require('react-app-rewired'); module.exports = function override(config, env) { config = injectBabelPlugin(['import', {libraryName: 'antd', style: 'css'}], config); return config; };
import { Button } from 'antd';
關於antd的按需加載其實還有其餘的方法,本文只介紹了兩種比較經常使用的配置方法,好比替換 react-scripts 包法和scripts 包 + override 組合法,具體能夠參考大佬的文章:https://zhaozhiming.github.io...網絡