React - Ant Design4.x版本安装使用,并按需引入和自定义主题
- 一. 安装使用 antd
 - 二.antd 高级配置
 - 安装 craco,对 create-react-app 的默认配置进行自定义
 - 自定义主题
 - 安装 babel-plugin-import ,按需加载组件代码和样式
 
Ant Design官网:https://4x.ant.design/docs/react/use-with-create-react-app
一. 安装使用 antd
-  
安装
antd
yarn add antd@4.24.3 -  
修改 src/App.css 文件,引入
antd/dist/antd.css@import '~antd/dist/antd.css'; -  
修改 src/App.js 文件,引入 App.css 样式文件,并使用
andt组件。import { Button } from 'antd'; import './App.css'; function App() { return ( <div className="App"> <Button type="primary">Button</Button> </div> ); } export default App; -  
页面正常显示
antd的蓝色按钮组件,说明已经把antd组件成功运行起来了。 
二.antd 高级配置
安装 craco,对 create-react-app 的默认配置进行自定义
-  
安装
craco
yarn add @craco/craco -  
修改 package.json 里的
scripts属性

 -  
在项目根目录创建一个
craco.config.js用于修改默认配置/* craco.config.js */ module.exports = { // ... }; 
自定义主题
定制主题: https://4x.ant.design/docs/react/customize-theme-cn
-  
安装
craco-less
yarn add craco-less -  
修改craco.config.js 文件,配置
lessOptionsconst CracoLessPlugin = require("craco-less"); module.exports = { plugins: [ { plugin: CracoLessPlugin, options: { lessLoaderOptions: { lessOptions: { // 自定义less变量 modifyVars: { "@primary-color": "#1DA57A" }, javascriptEnabled: true, }, }, }, }, ], }; -  
src/App.css 文件修改为
src/App.less,并修改样式引用为@import '~antd/dist/antd.less';

 -  
修改 src/App.js,引用文件为
src/App.less

 -  
yarn start重启项目访问页面,如果看到一个绿色的按钮就说明配置成功了。 
安装 babel-plugin-import ,按需加载组件代码和样式
-  
安装
babel-plugin-import
yarn add babel-plugin-import -  
修改craco.config.js 文件,配置
babel-plugin-importconst CracoLessPlugin = require("craco-less"); module.exports = { plugins: [ { plugin: CracoLessPlugin, options: { lessLoaderOptions: { lessOptions: { // 自定义less变量 modifyVars: { "@primary-color": "#1DA57A" }, javascriptEnabled: true, }, }, }, }, ], // 配置babel-plugin-import按需引用 babel: { plugins: [ ["import", { libraryName: "antd", libraryDirectory: "es", style: true }], ["@babel/plugin-proposal-decorators", { legacy: true }], ], }, }; -  
移除前面在 src/App.less 里全量添加的
@import '~antd/dist/antd.less';,yarn start重启项目访问页面,antd组件的js和css代码都会按需加载。 


















