Smarter Webpack versioning with webpack-git-hash

By Josh Kadis
September 20th, 2016, 11:00 am

Among the many reasons that Alley has adopted Webpack for our frontend builds is its asynchronous “chunk” loading capability. This reduces page rendering times across all pages of a large, complex site like Brookings.edu. But it comes with a caveat: Unless the filenames change with each new build, an old file might stay cached indefinitely on a CDN.

Webpack already offers a convenient [hash] config option that alleviates the CDN concern but does not offer an easy way to detect when the bundle was created and deployed.

We resolved this with webpack-git-hash, an open-source Webpack plugin that allows you to create unique file names using the most recent Git commit hash (or any other string you provide) instead of a Webpack hash. So if you do encounter a problem on a production site, you can quickly determine at what point in your Git commit history a Webpack file was created. Here’s a basic config:

output: {
    filename: 'bundle.[githash].js',
    chunkFilename: '[name]-chunk.[githash].js'
}

 

But that’s not all! webpack-git-hash has a couple other cool features. By setting a config option, you can instruct the plugin to delete obsolete versions of a file after the Webpack build finishes.

You can also add a callback function that receives the current version hash (and some other info). This gives you a chance to update other references to the versioned file (here’s an example).

Check it out on NPM or GitHub.