react 完成页面代码支解、按需加载

虽然一向有做 react 相干的优化,按需加载、dll 星散、服务端衬着,然则从来没有从路由代码支解这一块入手过,昨天在当地开辟时没有测试胜利,本日又搞了下,已布置到线上环境了,本日就这个纪录一下。

修正设置

  • 开辟环境:webpack@v3react-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>

    然后打包效果就会星散出各页面代码:

    《react 完成页面代码支解、按需加载》

    在页面中我们只须要载入进口文件 app.js ,其他剧本在接见到对应页面时都邑经过这个文件载入。

考证效果

在将静态资本上传到 cdn 以后,在页面中加载 app.cssapp.js ,运转以后接见各个页面就会顺次加载对应剧本,效果如图:

《react 完成页面代码支解、按需加载》

能够看到,在接见第一个页面时加载的页面剧本经 gzip 紧缩后唯一 21.8KB !!!固然这与页面复杂度也有关,然则相较于加载悉数剧本,已是大幅减少了,这类优化对接见目的性很强的用户感觉起来尤其显著。

这么做的另一个优点就是当我们只变动项目中某些页面的营业代码时,其他页面的代码依然是稳定的,所以这个时刻其他页面用的是客户端缓存,从另一个层面又做了一次优化。

Tips

该文章首发于我的博客https://blog.bingqichen.me/

    原文作者:BingqiChen
    原文地址: https://segmentfault.com/a/1190000014155234
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞