Service Worker Config File
The service worker configuration file provides several properties that allows developers to specify which caching strategies to implement and which resources to target.
Service worker configuration file
This is one of the essential files added by the @angular/pwa
schematic because the service worker configuration file (ngsw-config.json
) allows specifying the different caching strategies for the assets and network responses.
{"$schema": "./node_modules/@angular/service-worker/config/schema.json","index": "/index.html","assetGroups": [{"name": "app","installMode": "prefetch","resources": {"files": ["/favicon.ico","/index.html","/manifest.webmanifest","/*.css","/*.js"]}},{"name": "assets","installMode": "lazy","updateMode": "prefetch","resources": {"files": ["/assets/**","/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"]}}]}
The snippet above is exactly the file that the add schematics created for us as a starting point.
Let’s analyze the file in all its parts:
First, the $schema
property addresses the configuration schema in the node_module folder. It assists developers by providing validation and hints while editing the file. If you try to add an invalid attribute, the IDE should display a warning:
The index
property holds the path to the index page, usually index.html.
AssetGroups
assetGroups
array has two cache configuration objects:
name: app
This group targets static files that constitute the core of our application (“app shell”) and that we want to fetch proactively. The property "installMode": "prefetch"
retrieves the files while the service worker is installing and makes them available in the cache. The installation step is interrupted if the service worker fails to gather the files. However, on a page reload, a new attempt is triggered again.
If we want to include external resources, like web fonts, we can add a new attribute, url
, accepting a string array with resource paths in the glob format.
"resources": {"files": ["/favicon.ico","/index.html","/manifest.webmanifest","/*.css","/*.js"],"urls": ["https://fonts.googleapis.com/**"]}