Search code examples
angularhashgulpangular-service-workerpurifycss

Angular Service Worker - hash mismatch after PurifyCSS on dist/styles.*.css


When I build an Angular application with a service worker, it creates a hash table with the hash of each file to detect when a new version of the app is available. This hash table is in ngsw.json.

Here is an example of the hash valueas.

Has table

If I want to clean unused css with PurifyCSS then dist/styles.*.css will change file content and therefore its hash, but the ngsw.json has the old hash.

In this situation, the angular service worker will fail because there will be a hash mismatch.

How cand I avoid this situation? Should I update the hash manually in ngsw.json after I run PurifyCSS? Is there some mechanism to update this value automatically or can PurifyCSS be executed before angular-cli generates the hash for each file?

This question is oriented in general for any kind of modification made over the dist files cached by the service worker, because the hash will change and therefore there will be a hash mismatch. This implieas that the service worker won't work.

Thank you in advance.


Solution

  • I discovered something very useful that appears in the official Angular documentation. You can recreate the ngsw.json file with a simple command after making all the modifications you want on the files in the dist folder.

    ./node_modules/.bin/ngsw-config ./dist/<project-name> ./ngsw-config.json [/base/href]
    

    This regenerates the ngsw.json and the service worker works correctly again.

    https://angular.io/guide/service-worker-config