0

Not able to generate separate chunks for node_modules which are needed for initial page load.

In my react app, i am using webpack 5 module federation. As per the docs, to consume the eager dependencies, we have to create a bootstrap.js file which we can import asynchronously in index.js file.

bootstrap.js

import React from 'react'
import ReactDOM from 'react-dom'

import App from './App'

ReactDOM.render(<App />, document.getElementById('app'))

index.js

import('./bootstrap')

The problem is that i am using split chunks plugin to create separate chunk for node_modules, where are have all the node_modules which are required for initial page load. Whereas in using the above approach, it is considering evrything as async.

split chunks config

splitChunks: {
    ...webpackConfig.optimization.splitChunks,
    chunks: 'async',
    cacheGroups: {
        node_vendors: {
            test: /[\\/]node_modules[\\/]/,
            name: 'node_vendors',
            chunks: 'initial'
        },
   }
}

One workaround i found is that instead of creating a bootstrap file, we can have that code inside index.js, but we have to load react and react-dom asynchronously.

index.js

import App from './App'

const renderApp = async () => {
   const { default: React } = await import('react')
   const { default: ReactDOM } = await import('react-dom')

   ReactDOM.render(<App />, document.getElementById('app'))
}

renderApp()

But in this approach, i have to add a few other dependencies as eager inside module federation config. Because now evrything is not loading asyncronously.

Is this a good approach or is there any better way to handle this?

0 Answers0