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

1.8k views Asked by At

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.

2

There are 2 answers

0
Mr. Mars On BEST ANSWER

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

1
user2619824 On

I just ran into that problem with my Angular Service Worker. I learned about it the hard way (fun fact: NGSW won't work in offline mode and won't cache results).

Anyway, here's how I addressed this issue.

Since Angular inlines components' CSS inside the .js dist outputs, the stand alone .css file output by Angular contains any global styling (i.e. styles.css) and for example, Bootstrap CSS. What I did was run purifyCSS and copy the cleaned output into src/styles.css. This way you don't have to do any SHA1 hash modification in the ngsw.json after building. The drawback is that whenever you add say, a module that relies on different Bootstrap selectors, you'll need to redo this process.

Unfortunately this is kind of clunky but I haven't found out a way to integrate the purifying process into the 'prebuild' process.