react-router v4 按需加载

1. 先安装 bundle-loader 

2.安装后添加组件 bundle.jsx  这个组件是webpack官方提供

import React from 'react';
import PropTypes from 'prop-types';
 
class Bundle extends React.Component {
  state = {
  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({
    mod: mod.default ? mod.default : mod
   });
  });
 }
 
  render() {
  return this.state.mod ? this.props.children(this.state.mod) : null;
  }
}
 
Bundle.propTypes = {
 load: PropTypes.func,
 children: PropTypes.func
};
 
export default Bundle;



3.准备好了开始使用

在导入的路由页面组件前面加入bundle-loader?lazy!  如:import User from 'bundle-loader?lazy!../../views/User';

导入之后使用 Bundle 组件进行处理(当然Bundle 需要导入)

export const NeedLogin = (props) => (
  <Bundle load={Login}>
  { (Container) => <Container {...props} /> }
  </Bundle>
)

然后把NeedLogin 导出, 在路由组件里面导入使用即可




4.如何查看是否配置好了按需加载,方法狠简单你先配置两个页面路由的按需加载,然后在一个页面console一些文字,然后访问另外一个页面 看看会不会输出,如果没有东西输出就是配置成功了

5.我找了一下webpack 里面直接配置bundle-loader?lazy 可以找到的都是webpack1.*多的,官网也没找到webpack2.0 bundle-loader 的配置,不知道是不是我看错了,有知道的告知一下,谢谢

 有用请点赞,有错请帮忙留言指出,我好修改不误导别人 谢谢

猜你喜欢

转载自blog.csdn.net/zzh738579138/article/details/78021835