在 Angular 中构建渐进式 Web 应用
将你的 Angular 应用转换为 PWA
PWA 的两个主要要求是 Service Worker 和 Web Manifest。虽然可以手动将这两者添加到应用中,但 Angular 团队提供了一个 @angular/pwa 包来自动完成此过程。
@angular/pwa 包会自动为应用添加 Service Worker 和应用清单。
要将此包添加到应用中,请运行:
ng add @angular/pwa
添加此包后,运行 ionic build --prod,www 目录将准备就绪,可以部署为 PWA。
默认情况下,@angular/pwa 包附带 Angular 徽标作为应用图标。请务必更新清单以使用正确的应用名称并替换图标。
Service Worker 和许多 JavaScript API(例如地理位置)等功能要求应用托管在安全上下文中。通过托管服务部署应用时,请注意需要 HTTPS 才能充分利用 Service Worker。
Service Worker 配置
添加 @angular/pwa 后,会在项目根目录创建一个新的 ngsw-config.json 文件。该文件负责配置 Angular 的 Service Worker 机制如何处理缓存资源。默认情况下,会提供以下配置:
{
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": ["/favicon.ico", "/index.html", "/*.css", "/*.js"]
}
},
{
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": ["/assets/**", "/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"]
}
}
]
}
这里有两个部分:一个是应用特定资源(JS、CSS、HTML),另一个是应用按需加载的资源。根据你的应用,可以 自定义这些选项。更详细的指南,请阅读 Angular 团队的官方指南。
部署
Firebase
Firebase 托管为渐进式 Web 应用提供了许多优势,包括得益于 CDN 的快速响应时间、默认启用的 HTTPS 以及对 HTTP2 推送 的支持。
首先,如果尚未创建,请在 Firebase 中 创建项目。
接下来,在终端中安装 Firebase CLI:
npm install -g firebase-tools
如果你是第一次使用 firebase-tools,请使用 firebase login 命令登录你的 Google 账户。
安装 Firebase CLI 后,在你的 Ionic 项目中运行 firebase init。CLI 会提示:
"Which Firebase CLI features do you want to set up for this folder?" 选择 "Hosting: Configure files for Firebase Hosting and (optionally) set up GitHub Action deploys"。
创建一个新的 Firebase 项目或选择一个现有项目。
"Select a default Firebase project for this directory:" 选择你在 Firebase 网站上创建的项目。
"What do you want to use as your public directory?" 输入 "www"。
回答下一个问题将确保应用中的路由、硬重载和深层链接正常工作:
Configure as a single-page app (rewrite all urls to /index.html)?" 输入 "Yes"。
"File build/index.html already exists. Overwrite?" 输入 "No"。
Set up automatic builds and deploys with Github? 输入 "Yes"。
For which GitHub repository would you like to set up a Github Workflow? 输入你的项目名称。
Set up the workflow to run a build script before every deploy? 输入 "Yes"。
What script should be run before every deploy? 输入 npm ci && npm run build。
Set up automatic deployment to your sites live channel when a PR is merged? 输入 "Yes"。
What is the name of the get hooked branch associated with your sites live channel? 输入你的项目主分支名称。
系统会生成一个 firebase.json 配置文件,用于配置应用部署。
最后需要确保正确设置缓存头。为此,在 firebase.json 文件中添加一个 headers 片段。完整的 firebase.json 如下所示:
{
"hosting": {
"public": "www",
"ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
],
"headers": [
{
"source": "/build/app/**",
"headers": [
{
"key": "Cache-Control",
"value": "public, max-age=31536000"
}
]
},
{
"source": "ngsw-worker.js",
"headers": [
{
"key": "Cache-Control",
"value": "no-cache"
}
]
}
]
}
}
有关 firebase.json 属性的更多信息,请参阅 Firebase 文档。
接下来,运行以下命令构建 应用的优化版本:
ionic build --prod
最后,运行以下命令部署应用:
firebase deploy
完成后,应用即可上线。