web优化 之 懒加载

本文Demo的完整工程代码, 参考dva-lazy-loading

开始

dva new dva-lazy-loading

首页

cnpm i --save antd

cnpm i --save-dev babel-plugin-import
vim .roadhogrc
{
  "entry": "src/index.js",
  "env": {
    "development": {
      "extraBabelPlugins": [
        "dva-hmr",
        "transform-runtime",
        ["import", { "libraryName": "antd", "style": "css" }]
      ]
    },
    "production": {
      "extraBabelPlugins": [
        "transform-runtime",
        ["import", { "libraryName": "antd", "style": "css" }]
      ]
    }
  }
}
vim src/routes/IndexPage.js
import React from 'react';
import { connect } from 'dva';
import { Button } from 'antd';
import styles from './IndexPage.css';

function IndexPage() {
  return (
    

Yay! Welcome to dva!

); } IndexPage.propTypes = { }; export default connect()(IndexPage);
npm run build
File sizes after gzip:

  90.51 KB  dist/index.js
  10.11 KB  dist/index.css
npm start

此时打开浏览器访问地址http://localhost:8000/#/ 获取包大小如下

lazy-loading-01.png

第二页(非懒加载)

cnpm i --save lodash
vim src/routes/SecondPage.js
import React from 'react';
import { connect } from 'dva';
import _ from 'lodash';

function SecondPage() {
  return (
    
{_.indexOf(['hello', 'world'], 'hello')}
); } SecondPage.propTypes = { }; export default connect()(SecondPage);
vim src/router.js
import React from 'react';
import { Router, Route, Switch } from 'dva/router';
import IndexPage from './routes/IndexPage';
import SecondPage from './routes/SecondPage';

function RouterConfig({ history }) {
  return (
    
      
        
        
      
    
  );
}

export default RouterConfig;
npm run build
File sizes after gzip:

  114.49 KB  dist/index.js
  10.11 KB   dist/index.css
npm start

此时打开浏览器访问地址http://localhost:8000/#/或http://localhost:8000/#/second 获取包大小如下

lazy-loading-02.png

第二页(懒加载)

vim src/router.js
import React from 'react';
import { Router, Route, Switch } from 'dva/router';
import dynamic from 'dva/dynamic';
import IndexPage from './routes/IndexPage';

function RouterConfig({ history, app }) {
  return (
    
      
        
         import('./routes/SecondPage'),
            })
          }
        />
      
    
  );
}

export default RouterConfig;
npm run build
File sizes after gzip:

  92.5 KB   dist/index.js
  24.48 KB  dist/0.async.js
  10.11 KB  dist/index.css
npm start

此时打开浏览器访问地址http://localhost:8000/#/ 获取包大小如下

lazy-loading-03.png

此时打开浏览器访问地址http://localhost:8000/#/second 获取包大小如下

lazy-loading-04.png

参考

  • 懒加载

  • dva官方文档

  • react-async-component

更多文章, 请支持我的个人博客

你可能感兴趣的:(web优化 之 懒加载)