I have multi module application, where some of my modules are lazily loaded, and so the output files in dist folder looks like this 1.d2ef1******8da.chunk.js, 2.dsfd3******8da.chunk.js and like wise. The problem is, if I create a new build for the production, then the hash changes and so the file names. Suppose a user has not refreshed the page, they still will try to lazily load the old file which will be shown as file not found. In such case my page hangs. How should I handle it ?
You can make use of Angular Service Workers to change your app into a PWA (Progressive Web Application).
It makes use of angular service workers to alert users to reload if a new version of app is deployed.
For Ex:
@angular/service-worker
, add it to package.json
and install dependencies. Import ServiceWorkerModule
in AppModule:
import { ServiceWorkerModule } from '@angular/service-worker';
Register it in the AppModule imports array:
ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })
Use it in app root component:
import { Component, OnInit } from "@angular/core"; import { SwUpdate } from "@angular/service-worker"; export class AppComponent implements OnInit { constructor(private swUpdate: SwUpdate){} ngOnInit(): void { if (this.swUpdate.isEnabled) { this.swUpdate.available.subscribe(() => { if (confirm("A New version of site is available. Load New Version?")) { window.location.reload(); } }); } } }
If you are on angular 4 and cli ~1.6. The process should be same.
npm install @angular/service-worker
create a ngsw-config.json
file in your app's src directory.
{ "index": "/index.html", "assetGroups": [{ "name": "app", "installMode": "prefetch", "resources": { "files": [ "/favicon.ico", "/index.html" ], "versionedFiles": [ "/*.bundle.css", "/*.bundle.js", "/*.chunk.js" ] } }, { "name": "assets", "installMode": "lazy", "updateMode": "prefetch", "resources": { "files": [ "/assets/**" ] } }] }
Trying it Out With the configuration in place, we can build the app for production ( ng build --prod
) and test it out using a local static server using - npx http-server /dist
除了上面 #4 之外的大多数步骤都是由最新的 angular cli 命令( https://angular.io/api/service-worker )自动完成的:ng add @angular/pwa
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.