Reputation: 661
From https://webpack.github.io/docs/long-term-caching.html,
The first paragraph says
To effectively cache your files, they should have a hash or version in their URL.
What is the purpose of hash/version in the URL that enables browser to cache files long term?
Upvotes: 2
Views: 1033
Reputation: 12240
Usually it's not a good idea to cache files that could change in the near future for a longer period as your clients possibly don't load the latest version of these files. So caching your bundle.js
could lead to the problem that after an update of your code, the browser still loads your old bundle.js
due to some caching settings.
A good way to solve this (which is easy to use when using webpack) is to hash the resulting bundle and append this hash to the file name. So your first version is called bundle.ad736defe.js
and after any modification this name will also change, for example to bundle.dffe3983.js
. Having this in place, you can cache these files forever as every change to your code will result in a new file name and thus the client will use the cached one as long as the exact same file is referenced in your index.html and it will download the new version as soon as you changed anything that affects the bundle's content.
Webpack has that feature built in which is super easy to activate by providing an output file name containing the [hash]
pattern.
output: {
path: path.resolve(__dirname, "dist"),
publicPath: "/",
filename: "bundle-[hash].js"
}
This will put your hashed bundle into dist/bundle.<calculated_hash>.js
.
As you don't know the filename beforehand, you can make use of the great HtmlWebpackPlugin that will automatically insert the script tags with the correct hashes for you.
Upvotes: 5