1:为什么用到react-loadable?

在我们开发react页面时,我们会遇到一个问题,那就是打包后的js文件特别巨大,首屏加载会特别缓慢。这个时候我们应该讲代码进行分割,按需加载,将js 拆分成若干个chunk.js,用到就加载,react-loadable就可以很好地解决这个问题。

1)安装

1
$ yarn add react-loadable

2:实战用法(核心写法,中间会略去一部分)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import React from 'react'
import { Router, Route } from 'react-router'
import Loadable from 'react-loadable'
// 大布局
// 这个模块大部分页面会使用,不建议动态加载,否则会导致请求太多
import Container from '../containers'
const loadingStyle = {
height: '100%',
minHeight: 1000
}
const Loading = () => <div style={loadingStyle} />
//会员页
const VipPage1 = Loadable({
loader: () => import('../../../desktop/pages/vip'),
loading: Loading
})
const VipPage2 = Loadable({
loader: () => import('../../../mobile/pages/vip'),
loading: Loading
})
export default function factory(isMobile = false) {
const VipPage = !isMobile ? VipPage1 : VipPage2
return function(history) {
return (
<Route onEnter={enterRouteLog} onChange={changeRouteLog} component={Container}>
<Route path='/vip/toefl' component={VipPage} module='home' onEnter={enterLeafRouteLog} onLeave={leaveRouteLog} />
</Route>
)
}
}

以此识别页面的移动端还是PC端。react-loadable是以组件级别来分割代码的,这意味着,我们不仅可以根据路由按需加载,还可以根据组件按需加载,使用方式和路由分割一样,只用修改组件的引入方式即可
参考资料:使用react-loadable实现代码分割