How to do Cache Busting with Webpack ?

Jean-Charles
Powerspace Engineering
3 min readMar 18, 2016

--

NOTE : This guide is highly deprecated, webpack 4 will soon be here.

In the last couple of days, I was tackling the production deployment of a fast-evolving web application at Powerspace.
I use webpack to package all the ressources such as JS, HTML or CSS, and users encountered issues with the fact that browsers cache static resources. Consequently, assets did not refresh after each new versions got pushed online. We decided to tackle the issue using cache busting.

What did we want ?

Basically we wanted the resources to be requested like this:

bundle-14903095.js
bundle-14903095.css

To do so, we’ll start with webpack :

We use [hash:x] to create a hash with x, the number of characters you need. (x is optional)

You can also add a hash for HTML and images :

Then, we load our .scss or/and .css files using extract-text-webpack-plugin :

now, for generating external files :

Tips :

I don’t recommend using [hash] in development since it will increase the packaging time and hopefully, because you’re good and you’ve already disabled the cache in your favorite browser. You can use two separate config files, e.g. webpack.config.js and webpack.prod.config.js or use a variable to fetch the current state.

Example of webpack config using a variable :

I use npm as a task runner with the following tasks :

“scripts”: {
“build”: “rm -rf www/* && NODE_ENV=production webpack -p”,
“devserver”: “rm -rf www/* && webpack -w —-progress --colors”
}

The command “build” is for production and this is where I set the variable NODE_ENV to production. “devserver” is for development.

Here is the webpack configuration to switch between both :

As you can see, I create a .map to reduce the weight of my bundle, using devtool : “source-map”

Now that we have generated the bundle, the last thing we want is to include it into index.html. We use a functionality of htmlWebpackPlugin as follows :

And that’s it ! Webpack has appended a unique hash to all scripts, html and css files.

Bonus

There are other ways to do it. For example HtmlWebpackPlugin has an attribute hash (boolean) that will automatically append a unique webpack compilation hash to all included scripts and css files. It’s faster than adding [hash:x] but only includes css and js. You might need to hash other ressources as well.

Hope you like the article, feel free to talk about it here or on twitter : https://twitter.com/ByJCf

--

--