最近使用create-react-app+antd搭建项目,不过antd使用到的组件很少,所以样式需要用到按需加载,但是呢,网上找了很多的教程,要么有些是没有用的,要么有些就是不完整的。
大环境说明:我不想暴露webpack的配置项,所以没有使用npm run eject。
所以接下来如果想改create-react-app脚手架创建的项目中的配置就要用到一下几个插件:
1、react-app-rewired
2、babel-plugin-import
3、customize-cra
第一步:安装antd按需加载的插件babel-plugin-import
cnpm i babel-plugin-import --save-dev
第二步:安装react-app-rewired
cnpm i react-app-rewired --save-dev 同时需要改package.js中的script属性 "scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-app-rewired eject" },
第三步:安装customize-cra
npm install customize-cra --save-dev
安装以后需要在package.js同级目录下创建config-overrides.js
文件,接下来在这个文件中写我们自己的配置
const { override, fixBabelImports } = require('customize-cra'); module.exports = override( fixBabelImports('import', { libraryName: 'antd', libraryDirectory: 'es', style: 'css' }) )
之后在组件中测试
import { Button } from 'antd'; function App() { return ( <div> <Button>antd 实现样式的按需加载</Button> </div> ) } export default App;
这样就可以实现按需加载antd的组件,并且无需手动引入样式了。
放一张张我的项目对比图:
对比可见,使用了按需加载后,css的包体减小的不是一点点,美滋滋。。。

以上就是create-react-app+antd 实现样式的按需加载 【成功案例】的全部内容,欢迎大家一起探讨哈,啦啦啦
Id like to thank you for the efforts youve put in writing this website. I really hope to view the same high-grade blog posts from you in the future as well. In fact, your creative writing abilities has inspired me to get my own, personal site now 😉
An intriguing discussion is definitely worth comment. I do think that you should write more on this subject matter, it may not be a taboo matter but usually people dont discuss these issues. To the next! Many thanks!!