搭建react專案,react+antd按需載入和less配置
阿新 • • 發佈:2021-01-19
全域性安裝create-react-app
npm install -g create-react-app
建立專案
yarn create react-app react-antd-demo
安裝antd包
yarn add antd
由於antd使用了less,所以如果想配置主題的話,我們也需要安裝less,這裡我們使用antd官網推薦的craco,然後修改package.josn
檔案
yarn add @craco/craco craco-less
"scripts": {
- "start": "react-scripts start",
- "build": "react-scripts build",
- "test": "react-scripts test",
+ "start": "craco start",
+ "build": "craco build",
+ "test": "craco test",
}
在專案根目錄新建craco.config.js
const CracoLessPlugin = require('craco-less'); module.exports = { plugins: [ { plugin: CracoLessPlugin, options: { lessLoaderOptions: { lessOptions: { modifyVars: { '@primary-color': '#1DA57A' },//主題顏色 javascriptEnabled: true, }, }, }, }, ], }
配置完成以上步驟,專案裡就可以使用less開發了
實際專案中,為了縮小打包後的體積,往往需要用到按需載入,步驟如下:
1.安裝babel-plugin-import
yarn add babel-plugin-import
然後在craco.config.js
里加上
babel: { plugins: [ [ "import", { "libraryName": "antd","libraryDirectory": "es", "style": true //設定為true即是less } ] ] },
以上配置完成後,在引用元件時,無需在額外引入樣式檔案,babel會自動按需幫你完成樣式的引入
有時候我們還想配置打包檔案分析,這時候需要安裝webpack-bundle-analyzer,但create-react-app預設沒有暴露配置檔案,我們往往需要yarn eject 命令,暴露出配置檔案,但由於我們上面安裝了craco,所以在craco.config.js內配置也是可以的。
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
webpack: { plugins: [ new BundleAnalyzerPlugin(), ] },
完整craco.config.js配置如下
const CracoLessPlugin = require('craco-less'); // const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer") module.exports = { webpack: { plugins: [ // new BundleAnalyzerPlugin(), ] }, babel: { plugins: [ [ "import", { "libraryName": "antd", "libraryDirectory": "es", "style": true// true 針對less } ] ] }, plugins: [ { plugin: CracoLessPlugin, options: { lessLoaderOptions: { lessOptions: { modifyVars: { '@primary-color': '#FA8C16' }, javascriptEnabled: true, }, }, }, }, ], };