Home  >  Q&A  >  body text

Debugging method for webpack code splitting using React.lazy

<p>I'm using <code>React.lazy</code> to try and split some code out of my main application but it's not working the way I expect and I'm having a hard time figuring out how to debug it . </p> <p>My code is roughly as follows:</p> <pre class="brush:php;toolbar:false;">// 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'; ...</pre> <p>What I want is:</p> <ul> <li>vendors.chunk.js:react</li> <li>main.chunk.js:index.js</li> <li>main-1.chunk.js:component.js</li> <li>library-0.chunk.js:library/utils</li> <li>library-1.chunk.js:library/component</li> <li>index.html: main.chunk.js, library-0.chunk.js, vendors.chunk.js</li> <li>Asynchronous chunks: main-1.chunk.js, library-1.chunk.js</li> </ul> <p>What I get is: </p> <ul> <li>vendors.chunk.js:react</li> <li>main.chunk.js:index.js component.js</li> <li>library.chunk.js:library/utils libraries/components</li> <li>index.html: main.chunk.js, library.chunk.js, vendors.chunk.js</li> <li>Async blocks: None</li> </ul> <p>As a result, my initial page load requires loading all the JS, resulting in poor performance. </p> <p>How do I force webpack to split <code>library</code> into multiple chunks so that I can take advantage of async chunks? Better yet, how do I debug a problem like this? </p> <p>My configuration is roughly as follows:</p> <pre class="brush:php;toolbar:false;">splitChunks: { chunks: 'all', cacheGroups: { library: { test: /[\\/]library[\\/]/, }, }, }</pre></p>
P粉001206492P粉001206492389 days ago388

reply all(1)I'll reply

  • P粉795311321

    P粉7953113212023-08-30 14:02:04

    The problem is the unexpected inclusion of babel-plugin-dynamic-import-node, which converts dynamic imports (for async loading) into regular require within the node environment, preventing any async blocks from being generated. The solution is to remove it (or only include it when running unit tests).

    reply
    0
  • Cancelreply