react-router4 配合webpack require.ensure 实现异步加载的示例

(编辑:jimmy 日期: 2024/9/28 浏览:2)

实现异步加载的方法,归根结底大都是根据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

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

一句话新闻

微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。