React-router 4 按需加载的完成体式格局及道理(Code Splitting)

React-router 4

引见了在router4今后,怎样去完成按需加载Component,在router4之前,我们是运用getComponent的的体式格局来完成按需加载的,router4中,getComponent要领已被移除,下面就引见一下react-router4是入围和来完成按需加载的。

1.router3的按需加载体式格局

route3中完成按需加载只须要根据下面代码的体式格局完成就能够了。
const about = (location, cb) => {
    require.ensure([], require => {
        cb(null, require('../Component/about').default)
    },'about')
}

//设置route
<Route path="helpCenter" getComponent={about} />

2.router4按需加载体式格局(three steps)

one step:

建立Bundle.js文件,这个文件实际上是个经由过程bundle-loader包装后的组件来运用,下面会详细讲这个东西。
import React from 'react';
import PropTypes from 'prop-types';

class Bundle extends React.Component {
  state = {
    // short for "module" but that's a keyword in js, so "mod"
    mod: null
  }

  componentWillMount() {
    // 加载初始状况
    this.load(this.props);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.load !== this.props.load) {
      this.load(nextProps);
    }
  }

  load(props) {
    // 重置状况
    this.setState({
      mod: null
    });
    // 传入组件的组件
    props.load((mod) => {
      this.setState({
        // handle both es imports and cjs
        mod: mod.default ? mod.default : mod
      });
    });
  }

  render() {
    // if state mode not undefined,The container will render children
    return this.state.mod ? this.props.children(this.state.mod) : null;
  }
}

Bundle.propTypes = {
  load: PropTypes.func,
  children: PropTypes.func
};

export default Bundle;

second step:

import aContainer from 'bundle-loader?lazy!./containers/A'

const A = (props) => (
  <Bundle load={aContainer}>
      //这里只是给this.props.child传一个要领,末了在Bundle的render内里挪用
    {(Container) => <Container {...props}/>}
  </Bundle>
)

third step:

 render() {
    return (
      <div>
        <h1>Welcome!</h1>
        <Route path="/about" component={About}/>
        <Route path="/dashboard" component={A}/>
      </div>
    )
  }

3.router4按需加载方体式格局剖析

(1).起首解释一下按需加载,浅显的将就是我当前的location在Home,那末我只应该加载Home的东西,而不该该去加载About等等其他的。

(2).Bundle.js这个文件的作用

先看这段代码:

module.exports = function (cb) {
    __webpack_require__.e/* require.ensure */(2).then((function (require) {
        cb(__webpack_require__(305));
    }).bind(null, __webpack_require__)).catch(__webpack_require__.oe);
};

这里是我们经由过程import loadDashboard from 'bundle-loader?lazy!./containers/A'这类体式格局引入的container控件。我们运用了bundle-loader将A的源码转化成了上面的代码,详细完成人人能够看bundle-loader源码,代码很少。

上面说到Bundle.js实在就运用来处置惩罚这个文件的,这个文件须要一个callback的参数,在Bundle的load要领中,我们会设置这个callback,当路由要调到A Container这里的时刻,就回去加载A Container,然后挪用这个callback,这个callback会挪用setState要领,将我们之前传入的load设置给mod,然后衬着出来。

4.webpack举行bundle-loader一致设置

这里婚配的是src/routers/下面的containers文件夹下面一切的js文件,包含二级目次。

  {
      // 婚配routers下面一切文件
      // ([^/]+)\/?([^/]*) 婚配xxx/xxx 或许 xxx
      test: /containers\/([^/]+)\/?([^/]*)\.jsx?$/,
      include: path.resolve(__dirname, 'src/routers/'),
      // loader: 'bundle-loader?lazy'
      loaders: ['bundle-loader?lazy', 'babel-loader']
    }

5.部份源码

1.bundle-loader的源码

/*
    MIT License http://www.opensource.org/licenses/mit-license.php
    Author Tobias Koppers @sokra
*/
var loaderUtils = require("loader-utils");

module.exports = function() {};
module.exports.pitch = function(remainingRequest) {
    this.cacheable && this.cacheable();
    var query = loaderUtils.getOptions(this) || {};
    if(query.name) {
        var options = {
            context: query.context || this.options.context,
            regExp: query.regExp
        };
        var chunkName = loaderUtils.interpolateName(this, query.name, options);
        var chunkNameParam = ", " + JSON.stringify(chunkName);
    } else {
        var chunkNameParam = '';
    }
    var result;
    if(query.lazy) {
        result = [
            "module.exports = function(cb) {\n",
            "    require.ensure([], function(require) {\n",
            "        cb(require(", loaderUtils.stringifyRequest(this, "!!" + remainingRequest), "));\n",
            "    }" + chunkNameParam + ");\n",
            "}"];
    } else {
        result = [
            "var cbs = [], \n",
            "    data;\n",
            "module.exports = function(cb) {\n",
            "    if(cbs) cbs.push(cb);\n",
            "    else cb(data);\n",
            "}\n",
            "require.ensure([], function(require) {\n",
            "    data = require(", loaderUtils.stringifyRequest(this, "!!" + remainingRequest), ");\n",
            "    var callbacks = cbs;\n",
            "    cbs = null;\n",
            "    for(var i = 0, l = callbacks.length; i < l; i++) {\n",
            "        callbacks[i](data);\n",
            "    }\n",
            "}" + chunkNameParam + ");"];
    }
    return result.join("");
}

/*
Output format:

    var cbs = [],
        data;
    module.exports = function(cb) {
        if(cbs) cbs.push(cb);
        else cb(data);
    }
    require.ensure([], function(require) {
        data = require("xxx");
        var callbacks = cbs;
        cbs = null;
        for(var i = 0, l = callbacks.length; i < l; i++) {
            callbacks[i](data);
        }
    });

*/

2.A的源码

import React from 'react';
import PropTypes from 'prop-types';
import * as reactRedux from 'react-redux';
import BaseContainer from '../../../containers/ReactBaseContainer';

class A extends BaseContainer {
  constructor(props) {
    super(props);
    this.renderCustom = function renderCustom() {
      return (
        <div >
          Hello world In A
        </div>
      );
    };
  }
  render() {
    // 返回父级view
    return super.render();
  }
}

A.propTypes = {
  dispatch: PropTypes.func,
};

function mapStateToProps(state) {
  return { state };
}

export default reactRedux.connect(mapStateToProps)(A);

3.route.js的源码

import React from 'react';
import { BrowserRouter, Switch, Link } from 'react-router-dom';
import { Route } from 'react-router';
import PostContainer from '../containers/PostsContainer';
// 设置trunk文件的名字  the basename of the resource
import aContainer from './containers/A';
import bContainer from './containers/B';
import cContainer from './containers/C';
import Bundle from '../utils/Bundle';

const A = () => (
  <Bundle load={aContainer}>
    {Component => <Component />}
  </Bundle>
)

const app = () =>
  <div>
    {/* path = "/about" */}
    {/* "/about/" 能够,但"/about/1"就不能够了 exact 设置以后,须要途径相对婚配,多个斜杠没有关联,这里直接在浏览器内里设置另有题目*/}
    {/* path = "/about/" */}
    {/* "/about/1" 能够,但"/about"就不能够了 用了strict,path要大于即是的关联,少一个斜杠都不可 */}
    {/* exact 和 strick 都用了就必须如出一辙,连斜杠都一样 */}
    <Link to="/about/"> Link to about</Link>
    <Route  path="/" component={PostContainer} />
    <Route path="/about/" component={A} />
    {/* <Route path="/home" component={B} />
    <Route component={C} /> */}
  </div>
;
export default function () {
  // 用来推断当地浏览器是不是支撑革新
  const supportsHistory = 'pushState' in window.history;
  return (
    <BrowserRouter forceRefresh={!supportsHistory} keyLength={12}>
      <div>
        {app()}
      </div>
    </BrowserRouter>

  );
}

更新(按需加载)

oneStep

import React, { Component } from "react";

export default function asyncComponent(importComponent) {
  class AsyncComponent extends Component {
    constructor(props) {
      super(props);

      this.state = {
        component: null
      };
    }

    async componentDidMount() {
      const { default: component } = await importComponent();

      this.setState({
        component: component
      });
    }

    render() {
      const C = this.state.component;

      return C ? <C {...this.props} /> : null;
    }
  }

  return AsyncComponent;
}

Second Step

const Buttons = asyncComponent(() => import("./button"));

babel 中须要设置一下

"presets": [
        [
          "es2015"
        ],
        "stage-1", // 应用了es7的语法,所以必须有这个设置
        "react"
      ],
文章援用
    原文作者:zhiwei
    原文地址: https://segmentfault.com/a/1190000009539836
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞