devipriya
devipriya

Reputation: 71

How to add hash code in js bundle files for caching

Am new to webpack configuration, pls let me know how to add hashcode in the generated js bundle files so as to cache my static assets. Thanks in advance

Upvotes: 3

Views: 3766

Answers (1)

Pallikondan
Pallikondan

Reputation: 76

To add hashcode for your generated bundle, please add these lines into your webpack.config.js file.

output: {
    filename: '[name].[contenthash].js',
    path: path.resolve(__dirname, 'dist'),
}

For server caching

You need to split your main chunk into runtime chunk and vendor chunk. For doing this you need to add the following code in the optimization section of webpack.config.js file.

optimization: {
    runtimeChunk: 'single',
    moduleIds: 'hashed',
    splitChunks: {
        cacheGroups: {
            vendor: {
                test: /[\\/]node_modules[\\/]/,
                name: 'vendors',
                chunks: 'all',
            },
        },
    },
}

When every time you change the code other chunks/hash (vendor, runtime) doesn't change. So the client (browser) doesn't fetch unchanged chunk it loads from the cache.

Reference Link https://webpack.js.org/guides/caching/

Upvotes: 6

Related Questions