Search code examples
webpackwebpack-file-loader

file name using hash to avoid the cache


Source

[name].[ext]?[hash]

I have two questions about the expression:

  1. how could this help for avoid cache in the browser?
  2. actually in Windows OS,it will emmit a file that named as [name].[ext],without the ?[hash] portion.So,it is not a good solution?

Solution

  • When you require the file, webpack will copy the file to the output directory and return you the url. The returned url should have the MD5 hash of the file's contents, even if the copied file isn't named with the hash. If you use this url in your code to load the resource, browsers will cash on the entire url, not just the file name.

    So if you have a file named 'icon.png' you might want to replace it with a new icon, but retain the same file name. When you use the url with the hash (i.e. "icon.png?FE657AC13EB837AC", the browser will cache that on the client's computer using the full url. Since that includes the hash, if you change images the browser will download a new copy. Without the hash in the url, the browser can assume that 'icon.png' hasn't change and used the cached version and never check the server to see if it has been updated.

    If you just use the url to the file without the hash in your html, that defeats the purpose. You could generate a random number or use the current date for example in the query string to make the client download the file each time (or change the headers on the server to disable caching), but that isn't ideal. By using the MD5 hash of the file you allow the browser to cache the image as long as the image has the same hash, which for practical purposes means it is the same image.