Home > Blockchain >  Debugging webpack code splitting with React.lazy
Debugging webpack code splitting with React.lazy

Time:01-27

I am using React.lazy to try to split off some code from my main application, but it's not working the way I expect and I'm having trouble figuring out how to debug.

My code looks something like:

// index.js

import React from 'react';
import { LibraryUtils } from './library/utils';

const Component = React.lazy(() => import('./component'));
...

// component.js

import React from 'react';
import LibraryComponent from './library/component';
...

What I want:

  • vendors.chunk.js: react
  • main.chunk.js: index.js
  • main-1.chunk.js: component.js
  • library-0.chunk.js: library/utils
  • library-1.chunk.js: library/component
  • index.html: main.chunk.js, library-0.chunk.js, vendors.chunk.js
  • async chunks: main-1.chunk.js, library-1.chunk.js

What I get:

  • vendors.chunk.js: react
  • main.chunk.js: index.js component.js
  • library.chunk.js: library/utils library/component
  • index.html: main.chunk.js, library.chunk.js, vendors.chunk.js
  • async chunks: none

As a result, my initial page load needs to load all JS and therefore has worse performance.

How can I force webpack to split library into multiple chunks, so that I can leverage async chunks? Even better, how do I go about debugging something like this?

My config looks something like this:

splitChunks: {
    chunks: 'all',
    cacheGroups: {
        library: {
            test: /[\\/]library[\\/]/,
        },
    },
}

CodePudding user response:

The problem was an accidental inclusion of babel-plugin-dynamic-import-node, which transforms dynamic imports (required for async loading) into regular require's for node environments, thereby preventing any async chunks from being generated. The solution was to remove that (or only include it when running unit tests).

  • Related