react实现按需加载的3种方法
1.精确加载组件
import Button from 'antd/lib/button'
import 'antd/lib/button/style'
2.暴露配置,配合babel-plugin-import插件实现按需加载
babel-plugin-import是一个用于按需加载组件和样式的babel插件
暴露配置
npm run eject
安装插件
npm install babel-plugin-import -S
修改package.json
"babel": {
"presets": [
"react-app"
],
"plugins": [
[
"import",
{
"libraryName": "antd",
"libraryDirectory": "es",
"style":"css"
}
]
]
}
配置完之后直接引入:import {Button} from ‘antd’
3.通过babel-plugin-import+react-app-rewired实现按需加载
react-app-rewired在不用暴露的配置的情况下对webpack配置进行扩展
//安装插件:
npm install babel-plugin-import -S
//修改(添加)config-overrides.js文件
//引入react-app-rewired添加babel插件的函数
const {
injetBabelPlugin}=require('react-app-rewired')
module.exports=function override(config,env){
config=injetBabelPlugin([
[
"import",
{
"libraryName": "antd",
"libraryDirectory": "es",
"style":"css"
}
]
],config);
return config
}:
配置完之后直接引入:import {Button} from ‘antd’