全局安裝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, }, }, }, }, ], };