Search code examples
reactjswebpacklazy-loadingcode-splitting

Is there is any way to load all remaining chunk after main chunk is loaded or manually specify which chunk to load - Webpack


I have a separate chunk which can be loaded later or after the main chunk. Is there is any way to load that chunk after main chunk is loaded. and without triggering the component which requires that chunk.

i am using following way to load that chunk:

import React, { Component } from "react";

const asyncComponent = (importComponent) => {
  return class extends Component {
    state = {
      component: null,
    };

    componentDidMount() {
      // import component should be function refererce.
      // it returns promise
      importComponent().then((cpm) => {
        // it has default property to load component dynamically (cpm.default)
        this.setState({ component: cpm.default });
      });
    }
    render() {
      // render method renders the component dynamically.
      const C = this.state.component;
      return C ? <C {...this.props} /> : null;
    }
  };
};

export default asyncComponent;

Importing the module like this.

const Mymodule = asyncComponent(() => import(/* webpackChunkName: "mychunk" */ "../../../components/Mymodule"));

I want to load this chunk after main chunk is loaded but without rendering Mymodule.

i am using

  • webpack version 4.44.2
  • react version ^17.0.1

Solution

  • This post will help you.

    reactjs - React router base code-splitting (get first chunk and then get other chunks async in background) - Stack Overflow

    Annotation /* webpackPreload: true * / enables webpack to add prefetch into artifact.