Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a webpack chunk for a dependency of a single angular component

I am building an angular app, which contains a single component which depends on a library in my node_modules. I would like to create a single chunk specifically for the dependency so that my users are able to cache it, as the component may change regularly, but the dependency will only be updated every few weeks (whenever it has an update).

I have tried various splits in my webpack config, which always resulted in either all node_modules in a single chunk, or the the component and its dependency together in one chunk.

Is there a way to configure webpack to always split a vendor into its own chunk if it is not loaded initially?

like image 212
Marv Avatar asked Dec 11 '25 18:12

Marv


1 Answers

I achieved the desired effect with the following config:

optimization: {
        splitChunks: {
            cacheGroups: {
                initVendors: {
                    chunks: 'initial',
                    test: /[\\/]node_modules[\\/]/,
                },
                asyncVendors: {
                    chunks: 'async',
                    test: /[\\/]node_modules[\\/]/,
                },
            },
        },
    },

initVendors

With chunks: 'initial' we advise webpack to only group modules that are required for the initial pageload.

initVendors: {
    chunks: 'initial',
    test: /[\\/]node_modules[\\/]/,
}

asyncVendors

With chunks: 'async' we advise wepack to only group modules that can be loaded into the page async, while browsing, for features that are not required on pageload.

This will also place these modules into their own chunks, instead of bundling them with the code in your application that is using them. This allows long term caching of a chunk.

asyncVendors: {
    chunks: 'async',
    test: /[\\/]node_modules[\\/]/,
},
like image 65
Marv Avatar answered Dec 14 '25 11:12

Marv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!