DEV Community

Cezary Tomczyk
Cezary Tomczyk

Posted on

Cache busting in Angular for static assets

In general, there might be very different solutions to that problem, but try the following way:

  • Install npm package @sitelintcode/angular-static-assets-hash.
  • We'll use the CLI command npx createAngularStaticHashes.
  • By default, the package searches for static assets in the folder [angular root]/assets/images, but you can set any location through the parameter --staticAssetsPath=[path to static assets].
  • The package gathers a list of all files from a given location, but you can change that by adding the parameter –-globPattern=[glob pattern]. Default: /**/*

Once the file assets.json is created:

{
  "assets/images/example.png": "iY5RY0G8wePLPRkZSTgW2XYZFZ7kQOqXoJTFpQFG5nI",
  "assets/images/avatar.svg": "7A7qFs_iOghsdUtLG-7y-5cxT3FC8S_BRXl5ldsNY7Y",
  "assets/images/body-background.svg": "K2FTBtDsxgKLQFr4BUW1ptnLWqPCKPyGypHCBTfcctQ",
  "assets/images/icons.svg": "Ka-ngr7Fht6ucmN03kzJeMN7f2iOtnkD-D63QJ01jhM"
}
Enter fullscreen mode Exit fullscreen mode

then you need to use it in your app through the Angular Pipe.

The final URL for the static asset should contain unique URL parameter that forces the browser to fetch the latest file.

Example: <img src="assets/images/example.png?c=Ka-ngr7Fht6ucmN03kzJeMN7f2iOtnkD-D63QJ01jh" alt="Example image">

See further information's in the article "Cache busting in Angular for static assets".

Top comments (0)