Angular PWA

前言

这里假设我们已经使用Angular开发了SPA应用, 我们希望在此基础上使用PWA做一些增强以获得更好的用户体验, 更好的性能.

什么是Service worker

安装 pwa

进入Angular项目根目录, 执行以下命令安装@angular/pwa.

1
ng add @angular/pwa@13.3.1

这里最好指定@angular/pwa的版本与当前使用的angular一致, 否则会有兼容性问题.

该命令完成以下操作

  1. 添加@angular/service-worker到工程
  2. 在CLI中启用service worker构建支持
  3. 在application模块中导入并注册service worker
  4. 更新index.html文件:
    包括一个添加manifest.webmanifest文件的链接
    为主题颜色添加meta tag
  5. 添加图标文件
  6. 创建名为ngsw-config.json的service worker配置文件,该文件指定缓存行为和其他设置。

添加@angular/service-worker到工程

1
2
3
4
5
6
7
8
@@ -28,10 +28,11 @@
"@angular/material": "13.3.1",
"@angular/platform-browser": "13.3.1",
"@angular/platform-browser-dynamic": "13.3.1",
"@angular/platform-server": "13.3.1",
"@angular/router": "13.3.1",
+ "@angular/service-worker": "13.3.1",
"@nguniversal/express-engine": "^13.1.0",

在application模块中导入并注册service worker

src/app/app.module.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 import { UserService } from "./services/user.service";
import { SharedModule } from "./shared/shared.module";
import { CustomOverlayContainer } from "./utils/custom-overlay-container";
import { WindowService } from "./services/window.service";
import { FlexLayoutModule } from "@angular/flex-layout";
+import { ServiceWorkerModule } from '@angular/service-worker';
+import { environment } from '../environments/environment';

const DEFAULT_PERFECT_SCROLLBAR_CONFIG: PerfectScrollbarConfigInterface = {
wheelPropagation: true,
suppressScrollX: true,
};
@@ -50,11 +52,17 @@ const DEFAULT_PERFECT_SCROLLBAR_CONFIG: PerfectScrollbarConfigInterface = {

PerfectScrollbarModule,
- AppRoutingModule,
+ AppRoutingModule,
+ ServiceWorkerModule.register('ngsw-worker.js', {
+ enabled: environment.production,
+ // Register the ServiceWorker as soon as the application is stable
+ // or after 30 seconds (whichever comes first).
+ registrationStrategy: 'registerWhenStable:30000'
+ })
],
declarations: [
AppComponent,

创建名为ngsw-config.json的service worker配置文件, 更多配置说明请参考Angular Service Worker Configuration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
{
"$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/**",
"/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)"
]
}
}
]
}

更新index.html文件
包括一个添加manifest.webmanifest文件的链接
为主题颜色添加meta tag

1
2
3
4
5
6
7
8
   <link rel="icon" type="image/x-icon" href="favicon.ico">  
+ <link rel="manifest" href="manifest.webmanifest">
+ <meta name="theme-color" content="#1976d2">
</head>
<body>
<app-root></app-root>
+ <noscript>Please enable JavaScript to continue using this application.</noscript>
</body>

启动angular PWA

配置完成之后重新构建我们的项目 npm run build

构建完成之后再通过 npm run start 来启动我们的项目,启动成功后打开 http://127.0.0.1:8080 应该能够看到

注意: 如果使用的是angular 14.2以下的版本, 会遇到”Angular 无法注册 ServiceWorker : A bad HTTP response code (404) was received when fetching the script”的问题, 这是因为npm run start实际调用的是ng serve, 而该命令启动应用, 对于生成的ngsw-worker.js文件访问不了,
解决办法是使用http-server 启动应用, 进入dist/下, 如果开启了ssr进入dist//browser启动项目
npx http-server path-to-your-dist-folder
对于angular 14.2或以上的版本, 可以使用如下方式启动, 好处是您现在可以测试您的service worker并同时享受到热加载带来的好处。
ng serve

参考文档

Angular PWA 渐进式 Web 应用

Getting started with service workers

How to Use Ng Serve with Service Worker

作者

鹏叔

发布于

2022-10-16

更新于

2024-07-10

许可协议

评论