Antd 版本为V3
首先按antd 官方网址提供的方法,安装插件
官方地址:https://3x.ant.design/docs/react/use-with-create-react-app-cn
npm i react-app-rewired customize-cra --save
- 修改package.json
/* package.json */
"scripts": {
- "start": "react-scripts start",
+ "start": "react-app-rewired start",
- "build": "react-scripts build",
+ "build": "react-app-rewired build",
- "test": "react-scripts test",
+ "test": "react-app-rewired test",
}
- 在项目根目录创建一个 config-overrides.js , 新增配置如下
const { override, fixBabelImports } = require('customize-cra');
module.exports = override(
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: 'css',
}),
);
npm i babel-plugin-import --save
- 移除 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>
);
}
}
export default App;
按照官方引导,这样完成之后,重新启动项目,我的文件样式丢失。
- 将所有代码commit 后,使用 npm run eject ,暴露webpack.config.js文件,会有提示信息“复制所有依赖文件和相应的依赖到项目中”,确认就好。会出现config和script文件
- 在 webpack.config.js 做修改,搜索“babelrc”, 将值改为true
- 在‘babel-loader’ 的 plugins 中 写入
[
'import',
{libraryName:"antd", style:'css'}
],
效果图如下:
这样页面就有样式了~
同理,按需加载确实提升了首屏加载的效率,以下是对比图:
优化前:
优化后: