前提
首先你得进入到你的项目目录里面,才能开始安装AntD
1、全部加载
(1) 安装并引入 antd
从 yarn 或 npm安装并引入 antd
yarn add antd
(2) 修改 src/App.js
引入自己需要的antd组件(比如按钮)
import Button from 'antd/es/button'
(3)修改src/App.css
在src/App.css 文件顶部引入 antd/dist/antd.css
@import '~antd/dist/antd.css';
2、按需加载
以上步骤演示实例,加载了全部的 antd 组件的样式,比较简单粗暴,使用方便,但从性能角度来讲,按需加载组件肯定比加载全部组件性能要高,如果公司规定开发中不能有多余的css存在,那么就需要配置高级设置,需要对 create-react-app 的默认配置进行自定义,这里我们使用 react-app-rewired,具体步骤如下:
(1) 安装并引入 antd
从 yarn 或 npm安装并引入 antd
yarn add antd
(2)引入 react-app-rewired 并修改 package.json 里的启动配置
yarn add react-app-rewired customize-cra --save
--save是模块化安装,不加--save是全局安装
/ package.json文件中 /
"scripts": {
"start": "react-scripts start",//删掉替换为 react-app-rewired start 如下
"start": "react-app-rewired start",
"build": "react-scripts build",//删掉替换为 react-app-rewired build 如下
"build": "react-app-rewired build",
"test": "react-scripts test", //删掉替换为 react-app-rewired test 如下
"test": "react-app-rewired test",
}
(3)创建 config-overrides.js 文件
在项目根目录创建一个 config-overrides.js 用于修改默认配置。
const { override, fixBabelImports } = require('customize-cra');
module.exports = override(
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: 'css',
}),
);
(4)安装babel-plugin-import——按需引入的关键
.babel-plugin-import 是一个用于按需加载组件代码和样式的 babel 插件,安装它并修改 config-overrides.js文件。
yarn add babel-plugin-import
(上面第二部已经修改好了config-ocerrides.js文件,直接拷贝进 config-overrides.js即可)
(5)按需引入
移除前面在 src/App.css 里全量添加的 @import ‘~antd/dist/antd.css’; 样式代码,并且按下面的格式引入模块。
// src/App.js
import React, { Component } from 'react';
import Button from 'antd/es/button'; //移除
import { Button } from 'antd'; //按需引入即可
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<Button type="primary">Button</Button>
</div>
);
}
}
复制代码
|