Regenerate content hash in ngsw after build or during deploy

Viewed 1336

We have an Angular application that uses the angular service worker.

As we know, this service worker compares content hashes from cached files against the hashes in the ngsw.json file.

Now, we have set-up continuous integration and delivery (with Azure DevOps, but shouldn't matter) and during the delivery phase, we're modifying some settings in an environment.json file (like color scheme, API url... all related to the deployment target). The problem is, by modifying that json file, the hash no longer matches with the hash for that file in the ngsw.json file.

We definitely don't want to rebuild for a dedicated target environment as that defeats the purpose in CI/CD. (You don't want to rebuild a package for a production environment once that package went to the QA process).

So the question is: is there a way to regenerate the hashes in the ngsw.json file after we have modified our environment.json (or any other) file? Or is there an other solution to this problem?

2 Answers

Are you talking about the following command:

node_modules/.bin/ngsw-config dist src/ngsw-config.json

You can place the command in your package.json:

  "scripts": {
    "ngsw-config": "node_modules/.bin/ngsw-config dist src/ngsw-config.json"
  }

This redoes the config and hashes for you. Run it after your final command, this should be possible in your CI environment.

Note also it can take a base href parameter if you use one of those.

More explanation here: Angular doc

Another way to update the hashes inside ngsw.json without having to ship the whole Angular CLI Package is to use this small open-source tool to recreate just the hashes.

wget https://github.com/dev-jan/ngsw-rehash/releases/download/v1.0/ngsw-rehash-linux-x86 -o ngsw-rehash
chmod +x ngsw-rehash
ngsw-rehash <path-to-dist>/ngsw.json

It's a small standalone binary without any dependencies. The sources can be found here: https://github.com/dev-jan/ngsw-rehash

I created this tool because I had the same problem and don't want to use the ngsw-config tool to keep my final Docker image small and without many unneeded binaries.

Related