Warm tip: This article is reproduced from stackoverflow.com, please click
cache-control webpack caching hash

Long term caching with webpack chunkhash and cache control

发布于 2020-03-27 15:43:09

I am using webpack to bundle all of my files. Inside webpack I use chunkhash, Md5Hash and manifest to produce unique chunkhash for each of my files that get download by browser. It would look like this.

styles.3840duiel348fdjh385idfki.css
bundle.488503289dfksdlkor93lfui.js
vendor.sdkkfuuewkf892377rfkjdle.js
image.dkkdiiue9984ujjkfld003kfpp.png

This means that browser can cache them and if the hash is not changed it will use the cached version.At the same time I can for example just change styles and only that hash will be changed so when I deploy the app browser will download only the new styles.

The problem is that on my server i use this:

Cache-Control: public max-age=31536000

This represents aggressive caching and the browser will use cached version for one year unless URL, file name is changed. When I for example change styles my hash is changed and browser should request the new styles from server. That is according to this article(pattern 1) and a few more that I found https://jakearchibald.com/2016/caching-best-practices/

My problem is that when I update something, example styles, hash for styles is changed and I deploy that. The browser will not request new styles unles I hit reload while on my page. It will server the cached files. How can I fix this?

I can use Cache-Control: no-cache but that is not a solution because than browser has to check with server every time if he can use cached version. That is 4 http requests that are not needed every time someone visits the page.

Questioner
Igor-Vuk
Viewed
62
Igor-Vuk 2017-07-07 18:18

I did it like this. I use different webpack config for my client and server bundle. For my client bundle that has bundle.js, vendor.js, styles.css... I use chunkhash and Cache-Control: public max-age=31536000 as described in my question. For my server bundle that serves html(ejs) I use Cache-Control: no-cache. This works good because browser will contact server on every reload but that will be only one http request. If nothing is changed browser uses the cached version of all the assets since chunkhash in html didn't changed.

If for example I update styles and chunkhash is changed browser will see that when in contacts the server on reload and only new styles will be downloaded.