Angular-Serviceworker:start_url 离线时不响应 200

Angular-Serviceworker: start_url does not respond with a 200 when offline

版本

描述

我使用 ng add @angular/pwa --project [app] 实现了 service-worker,Lighthouse 会将网络应用程序识别为 PWA。 突然,在部署到托管 "install" 的 Firebase 之后,通知没有弹出,所以我检查了开发控制台。

清单仍然照常显示:

但没有缓存任何内容:

当 运行 Lighthouse-Audit 时,出现以下错误:

start_url does not respond with a 200 when offline

ngsw-config.json

{
  "$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/**",
          "/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
        ]
      }
    }
  ]
}

manifest.webmanifest

{
  "name": "App",
  "short_name": "App",
  "theme_color": "#5787b2",
  "background_color": "#fafafa",
  "display": "standalone",
  "scope": "/",
  "start_url": "/",
  "icons": [
    {
      "src": "assets/icons/icon-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "assets/icons/icon-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ]
}

所以我在对类似问题的评论中找到了解决我的问题的方法:

app.module.ts 中将 registrationStrategy: 'registerImmediately' 添加到 ServiceWorker 的注册中,如下所示:

ServiceWorkerModule.register('ngsw-worker.js', { enabled: env.production, registrationStrategy: 'registerImmediately' }),

就我而言,我的 app.module 导入中包含以下内容:

ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })

除了 prod 变量返回 false 因为正在使用的环境不是 --prod。确保 env.production 实际上在应有的位置返回“true”。一个好的起点是“脚本”中的 package.json。检查命令是 运行 --configuration=prod-env 或者您已经配置了它。