虽然一向有做 react 相干的优化,按需加载、dll 星散、服务端衬着,然则从来没有从路由代码支解这一块入手过,昨天在当地开辟时没有测试胜利,本日又搞了下,已布置到线上环境了,本日就这个纪录一下。
修正设置
- 开辟环境:
webpack@v3
、react-router@v4
装置依靠:
$ yarn add babel-plugin-syntax-dynamic-import -dev
- 修正
.babelrc
文件:在plugins
中增加"syntax-dynamic-import"
革新项目代码
装置依靠:
$ yarn add react-loadable
依据
react-loadable
文档提醒,我们须要供应一个载入新页面时的Loading
组件,同时对加载和超时状况举行区分提醒:import React from 'react'; import { Icon } from 'antd'; const Loading = ({ pastDelay, timedOut, error }) => { if (pastDelay) { return <div><Icon type="loading" /></div>; } else if (timedOut) { return <div>Taking a long time...</div>; } else if (error) { return <div>Error!</div>; } return null; };
变动页面组件导入要领:
import React from 'react'; import Loadable from 'react-loadable'; import { Route, Switch } from 'react-router-dom'; const Home = Loadable({ loader: () => import('../Home'), loading: Loading, timeout: 10000 }); const EditArticle = Loadable({ loader: () => import('../EditArticle'), loading: Loading, timeout: 10000 }); ... <Switch> <Route exact path="/home" component={Home} /> <Route path="/editarticle" component={EditArticle} /> </Switch>
然后打包效果就会星散出各页面代码:
在页面中我们只须要载入进口文件
app.js
,其他剧本在接见到对应页面时都邑经过这个文件载入。
考证效果
在将静态资本上传到 cdn 以后,在页面中加载 app.css
和 app.js
,运转以后接见各个页面就会顺次加载对应剧本,效果如图:
能够看到,在接见第一个页面时加载的页面剧本经 gzip 紧缩后唯一 21.8KB !!!固然这与页面复杂度也有关,然则相较于加载悉数剧本,已是大幅减少了,这类优化对接见目的性很强的用户感觉起来尤其显著。
这么做的另一个优点就是当我们只变动项目中某些页面的营业代码时,其他页面的代码依然是稳定的,所以这个时刻其他页面用的是客户端缓存,从另一个层面又做了一次优化。
Tips
-
react-loadable
另有其他设置选项,能够按需设置; - 这里还须要注意的一点是:
webpack
中的output.publicPath
选项,这个设置会影响app.js
从那边加载页面剧本,准确的写法应当是剧本文件载入的前缀地点,比方:0.js
的长途链接为 http://static.domain.com/rele… ,那末这个应当设置为 http://static.domain.com/rele… 。
该文章首发于我的博客https://blog.bingqichen.me/