PWA (Progressive Web App)
Implementing Progressive Web App (PWA) functionality within Angular is remarkably straightforward. The Angular CLI simplifies the process by automatically configuring all necessary elements with a single command. This guide details how to integrate a PWA into an existing Angular project and verify its proper operation.
Project Setup
First, generate a new Angular project. If you have an existing project, you can skip this step.
ng new project-pwa
PWA Integration
Within your project, add PWA support using the Angular CLI. Specify the project name with the --project
option.
ng add @angular/pwa --project [project-pwa]
Verification
Upon successful integration, confirm the existence of the following files. Their presence indicates that PWA functionality has been successfully added to your project.
ngsw-config.json
file- In
angular.json
, verify that"serviceWorker": true
is present in the build configuration.
Initial Module Configuration
Examine your project’s root module (typically AppModule
) and ensure it includes the following or similar code. Note that specific versions of Angular might require manual addition if this code is absent.
import { ServiceWorkerModule } from '@angular/service-worker';
@NgModule({
declarations: [],
imports: [
ServiceWorkerModule.register('/ngsw-worker.js', { enabled: environment.production })
],
providers: [],
})
export class AppModule { }
Implementing Version Update Checks within a Component
In the primary component, implement version update detection. This ensures that the application recognizes when a new version is available.
import { Component, OnInit } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
updateMessage: string;
constructor(
private swUpdate: SwUpdate
) {
}
ngOnInit() {
if ('serviceWorker' in navigator) {
console.log('service worker!!!!!!!!!!!!!');
if (this.swUpdate.isEnabled) {
this.swUpdate.available.subscribe(() => {
if (confirm('New version available. Load New Version?')) {
window.location.reload(); // Reloading discards cached data and loads the new version.
}
});
}
}
else {
console.log('service worker is not ready');
}
}
}
Building the Application
Build the application as you normally would for your target environment.
ng build --prod
Testing the PWA
Follow these steps to test the PWA functionality. Be aware that updates to the code may not be immediately recognized due to Angular’s default update policy, which introduces a delay. You can adjust the SwUpdate
configuration within your PWA-related code to modify this behavior.
- Deploy the application using a local HTTP server (e.g.,
http-server
) or a real server environment. - Upload the built code to the server.
- Access the application in a web browser.
- Modify the code or cached data, rebuild the application, and upload the updated code.
- Reload the application in the browser.
- Verify that the browser prompts you to update to the new version within a few seconds.
- Confirm that clicking “yes” updates the application.
Modifying Cached Data
You can directly modify the cached data by editing the ngsw-config.json
file. Add or remove entries in the external
section to control which data is cached.
"external": {
"urls": [
{"url": "https://fonts.googleapis.com/..."},
{"url": "https://fonts.gstatic.com/s/..."}
]
}
Disabling Caching
Conversely, you can disable caching for specific resources:
{
"name": "offline",
"urls": { "https://mysite.com/data.json": {"match": "prefix"}},
"cache": {
"optimizeFor": "freshness",
"maxAgeMs": 360000000,
"maxEntries": 1,
"strategy": "lru"
}
}
Cache Classification
app
: Includes files critical to the application’s structure, such as HTML, CSS, JavaScript, TypeScript, and favicons.assets
: Encompasses files located in theassets
directory or files that are loaded on demand.
Loading Modes
lazy
: Use this mode for files loaded only when required.prefetch
: Initiates a single request. Setting updates toprefetch
is recommended.
댓글남기기