虽然一直有做 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 文档 https://github.com/jamiebuilds/react-loadable/blob/master/README.md 提示, 我们需要提供一个载入新页面时的 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/release/0.js , 那么这个应该配置为 http://static.domain.com/release/.
来源: http://www.jb51.net/article/137673.htm