实现异步加载的方法,归根结底大都是根据webpack的require.ensure来实现

第一个是自己使用require.ensure实现,

第二种 使用loader实现

今天我们说的是使用bundle-loader来实现,这样代码更优雅些。

首先需要安装bundle-loader ,具体使用npm还是yarn,就看你的包管理使用的是啥了。

下面需要一个bundle.js

import React, { Component } from 'react';
export default class Bundle extends Component {
  constructor(props) {
    super(props);
    this.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 "htmlcode">
bundle-loader"htmlcode">
import Bundle from './components/bundle.js';
import ListComponent from 'bundle-loader"htmlcode">
<Route path="/list" component={List} />

以及配置output的chunkFilename

chunkFilename: '[name]-[id].[chunkhash:4].bundle.js'

chunkFilename配置好以后,异步加载进来的文件名称就会按照上面的命名方式来展示,如果不配置,就是webpack给生成的数字了。

上面的都配置好了以后,就是怎么使用bundle了,你看到route上配置的component对应的是List,所以我们需要写一个List:

const List = (props) => (
  <Bundle load={ListComponent}>
    {(List) => <List {...props}/>}
  </Bundle>
);

到这里基本上就配置完了,这个时候你本地重启服务,然后点击对应的路由,就会看到异步记载的js:List-0.094e.bundle.js

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

标签:
react-router4,webpack,require.ensure,异步加载

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
狼山资源网 Copyright www.pvsay.com