Instructor: When we open the Chrome dev tools and go to the audit tab, we can run a Lighthouse test on our app. We get quite a decent score already, but there is still some things to improve.
Since Angular CLI version 6, we can simply run ng add @angular/pwa to convert our app into a progressive web app. This will install the packages @angular/pwa and @angular/service-worker. It will import the service worker module in our app module, and only enable it when running in production mode.
In the file manifest.json, we can define how our PWA behaves when it gets installed on a user's device. Let's capitalize the value of the name property, and set our theme color to 343840. This is also where the icons of various sizes are defined.
Inside our index.html, we also have a theme color defined. Let's also set this to 343840.
When we run npm run builds and npm start, we can browse to a production build on our local machine. In our dev tools in the application tab, we can see our service-worker running.
Service-worker can help running an application when the browser is in offline mode. However, once we tell our browser to go offline, we see that an error now comes up, because it's still trying to download data from our API.
We can cache our API and assets in the service-worker configuration file ngsw-config.json. Inside the assetGroups array, we define a new object with the name, "externals."
We set installMode and updateMode both to prefetch. In the resources object, we add a URLs property, which is an array of strings. This will prefetch these CDN URLs and cache the data.
The next object has the name images, and installMode and updateMode set to prefetch. In resources, the URLs will link to the API so that our images will be cached, too.
Below the assetGroups, we'll create a dataGroups object, which is an array. Inside the array, we create an object with the name set to REST API. We add an array called URLs and add our API endpoints. In the cache config objects, we set strategy to freshness, maxSize to 100, maxAge to one hour, and time-out to five seconds.
We refresh our app and click run to hydrate the cache. Then we can set the browser to offline. When we reload, we see that the resources from our API are cached by the service-worker. Let's re-deploy our app and run a new Lighthouse audit. We see that PWA score improves to 91 percent.
We deploy our app again and run another Lighthouse test. To improve the SEO score, we need to add a robots.txt file. In our source directory, we add a file called robots.txt, set the content to user-agent*, and allow /.
We then open angular.json, and in our builds object in the assets array, we add source/robots.txt. In the text object in the assets array, we add the same robots.txt. When we redeploy the app and run another Lighthouse audit, we can see that the SEO and PWA scores are now both 100 percent.