Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache busting of JSON files in webpack

I have the following code (written in typescript, but could be any JS variant):

this.http.get('configs/config.json').subscribe(...);

Basically, I'm loading a configuration from a local json file. I would like to have cache busting implemented on the file. Although I can set up my webpack to modify json files by adding a hash suffix, I would also need to modify all the source files which have references to those files. string-replace-loader might do the job, but doing this feels bit odd.

Additionally, in some cases I don't have access to the code lines that make the http call to resource (third-party plugin for e.g. translation that load something like i18n/[lang].json so I can't directly modify code and/or name (and thus content hash) is only known in the run-time.

Is there something like URL rewrite for webpack that could solve this?

like image 611
Miroslav Jonas Avatar asked Dec 19 '16 10:12

Miroslav Jonas


People also ask

What is cache busting in webpack?

Cache busting means making sure the users browser loads the newest version of our app, if it has been updated, instead of using a cached version. A naive webpack setup would just use a single output file with a fixed name. const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.

Can JSON be cached?

In order to add data in cache as JSON, the objects need to be created according to the JSON standards provided by NCache. JsonObject is added in the cache against a unique key. This key will be used to perform further operations on the cache.

What is the purpose of cache busting?

Cache busting solves the browser caching issue by using a unique file version identifier to tell the browser that a new version of the file is available. Therefore the browser doesn't retrieve the old file from cache but rather makes a request to the origin server for the new file.


1 Answers

You can use query-params in the URL to avoid caching. No need to change the filename.

this.http.get(`configs/config.json?t=${new Date().getTime()}`).subscribe(...);

new Date().getTime() will create a unique number for every millisecond.

In case of ngx-translate, you can define your httpLoader factory as

export function HttpLoaderFactory(httpClient: HttpClient) {
  return new TranslateHttpLoader(httpClient, '/assets/i18n/',`.json?v=${new Date().getTime()}`);
}

I hope that helps.

like image 128
Kumar Sidharth Avatar answered Oct 20 '22 17:10

Kumar Sidharth