1. 安装
npm install antd --save
或者
yarn add antd
2. 按需加载方式一:安装 babel-plugin-import
npm install babel-plugin-import --save
.babelrc or babel-loader option:
{
"plugins": [
["import", {
"libraryName": "antd",
"libraryDirectory": "es",
"style": "css" // `style: true` 会加载 less 文件
}]
]
}
然后只需从 antd 引入模块即可,无需单独引入样式。
// babel-plugin-import 会帮助你加载 JS 和 CSS
import { DatePicker } from 'antd';
等同于下面手动引入的方式。
import DatePicker from 'antd/es/date-picker'; // 加载 JS import 'antd/es/date-picker/style/css'; // 加载 CSS
按需加载,方式二:
需要对 create-react-app 的默认配置进行自定义,这里我们使用 react-app-rewired
1. 引入 react-app-rewired 并修改 package.json 里的启动配置
yarn add react-app-rewired customize-cra --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",
}
2. 然后在项目根目录创建一个 config-overrides.js 用于修改默认配置。
const { override, fixBabelImports } = require('customize-cra');
module.exports = override(
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: 'css',
}),
);
3.babel-plugin-import 是一个用于按需加载组件代码和样式的 babel 插件,安装它并修改 config-overrides.js文件(步骤2已修改)。
yarn add babel-plugin-import --save
4.移除前面在 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>
);
}
}
5.这样就配置完成了,最后重启 npm start 访问页面,antd 组件的 js 和 css 代码都可以按需加载,提高网页性能。