Search code examples
javascriptwebpackbrowser-cache

How to use Cache-Busting with Webpack?


Before Webpack I would always rely on the following pattern for "cache-busting":

<script src="foo.js?cacheBust=12345" />

where 12345 was a token the sever generated for me on every build (it could be a Git hash, although in my case it isn't).

With Webpack I now have two files: build.js and chunk.1.js. Since I bring the first one in with a normal script tag I can use the above pattern:

<script src="build.js?cacheBust=12345" />

However, at that point build.js goes and fetches chunk.1.js, and when it does it doesn't include the cache-busting suffix.

I would like for Webpack to automatically append the ?cacheBust=12345, but I don't know the 12345 part at build time, so I can't include it in my webpack.config. Instead, I have to wait until the HTML page is evaluated, at which point I get the token from the server.

So, my question is, is there any way to have Webpack look at the parameter used to fetch the initial file (eg. ?cacheBust=12345) and append that same parameter when fetching other files?


Solution

  • You can simply do this

    output: {
        filename: '[name].js?t=' + new Date().getTime(),
        chunkFilename: '[name]-chunk.js?t=' + new Date().getTime(),
        publicPath: './',
        path: path.resolve(__dirname, 'deploymentPackage')
    }