webpack generating chunks for nested link

Viewed 99

I am doing route-based code splitting using React.lazy. In some pages, there are link to other pages. In that case, Its creating chunk for that linked page also.

webpack

optimization: {
      runtimeChunk: 'single',
      splitChunks: {
        cacheGroups: {
          vendor: {
            test: new RegExp(
              /[\\/]node_modules[\\/]/,
            ),
            chunks: 'all',
            name: 'vendor',
            enforce: true,
          },
        },
      },
    },

Routes.js

const Home = React.lazy(() => import('./Pages/Home' /* webpackChunkName: "home" */));
const Profile = React.lazy(() => import('./Pages/Profile' /* webpackChunkName: "profile" */))
const Settings = React.lazy(() => import('./Pages/Settings' /* webpackChunkName: "Settings" */))


const Routes = () => {
    return (
        <Suspense fallback={<div>loading...</div>}>
            <Switch>
                <Route path="/" exact component={Home}/>
                <Route path="/Profile"  component={Profile}/>
                <Route path="/Settings"  component={Settings}/>
            </Switch>
        </Suspense>
    )
}

Home

export default function Home() {
    return (
        <div>
            <p>Home</p>
            <Link to="/profile">Go to Profile</Link>
            <Link to="/settings">Go to Settings</Link>
        </div>
    )
}

Here I am getting below chunks -

app.[hash].js
runtime.[hash].js
vendor.[hash].js
Home.[hash].js
Profile.[hash].js
Home~Profile.[hash].js
Home~Setting.[hash].js

What is the reason of getting last two chunks?

1 Answers

You can inspect content of this chunks by some webpack bundle analyzer too see whats inside. Most likely there is some vendor packages similar between two pages so from performance perspective it is better to put this packages in shared chunk instead of duplicating those packages in each chunk.

Related