1、创建项目
npx create-react-app demo
或
yarn create-react-app demo
创建项目没什么坑
2、安装antd
// 安装
yarn add antd
没什么坑
3、antd按需引入
- 使用 craco 对 create-react-app 的默认配置进行自定义
// 安装craco
yarn add @craco/craco
/* package.json中配置 */
"scripts": {
- "start": "react-scripts start",
- "build": "react-scripts build",
- "test": "react-scripts test",
+ "start": "craco start",
+ "build": "craco build",
+ "test": "craco test",
}
- 安装 yarn add babel-plugin-import 用于按需加载
yarn add babel-plugin-import
- 在项目根目录创建一个 craco.config.js 用于修改默认设置
module.exports = {
babel: {
plugins: [
[
"import",
{
"libraryName": "antd",
"libraryDirectory": "es",
"style": "css" //设置为true即是less
}
]
]
},
};
4、自定义主题
- 自定义主题类似 less-loader 提供的 less 变量覆盖功能。引入 craco-less 来帮助加载 less 样式和修改变量
yarn add craco-less
- 在 craco.config.js 进行配置
const CracoLessPlugin = require('craco-less');
module.exports = {
plugins: [
{
plugin: CracoLessPlugin,
options: {
lessLoaderOptions: {
lessOptions: {
modifyVars: { '@primary-color': '#1DA57A' },
javascriptEnabled: true,
},
},
},
},
],
};
5、加载完毕禁止打开浏览器
- 根据 craco-antd 配置全局变量 BROWSER = ‘none’
/* 创建.env文件 */
BROWSER=none
/* craco.config.js */
process.env.BROWSER = "none";