1

我有下面的 Angular Service Worker 配置文件,它似乎对 api 请求和静态内容工作正常,但对于导航 url,它没有命中缓存。例如,如果我打开www.mydomain.comwww.mydomain.com/sectionwww.mydomain.com/account/section请求会转到服务器而不是在本地解析,因此应用程序的离线版本不起作用。

{
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "updateMode": "prefetch",
      "resources": {
        "files": [
          "/index.html",
          "/manifest.json",
          "/favicon.ico",
          "/*.css",
          "/runtime-es2015*.js",
          "/polyfills-es2015*.js",
          "/main-es2015*.js",
          "/common-es2015*.js",
          "/content/images/header-pattern.png",
          "/content/fonts/roboto-v20-latin-regular.woff2",
          "/content/fonts/raleway-v14-latin-regular.woff2",
          "/content/fonts/material-icons.woff2",
          "/content/images/logo-round-toolbar.png",
          "/content/images/facebook.png",
          "/content/images/linkedin.png",
          "/content/images/twitter.png"
        ]
      }
    },
    {
      "name": "app-lazy-assets",
      "installMode": "lazy",
      "updateMode": "prefetch",
      "resources": {
        "files": [
          "/*.js",
          "/content/**"
        ],
        "urls": [
          "https://cdnjs.cloudflare.com/**",
          "https://fonts.googleapis.com/**",
          "https://fonts.gstatic.com/**"
        ]
      }
    }
  ],
  "dataGroups": [
    {
      "name": "my-api-30days",
      "urls": [
        "/api/url/part/*",
        "/api/url/*",
        "/api/url/segment/*"
      ],
      "cacheConfig": {
        "strategy": "performance",
        "maxSize": 300,
        "maxAge": "30d"
      }
    },
    {
      "name": "my-api-5days",
      "urls": [
        "/api/account/5dayscacheurl"
      ],
      "cacheConfig": {
        "strategy": "performance",
        "maxSize": 300,
        "maxAge": "5d"
      }
    }
  ],
  "navigationUrls": [
    "/**",
    "!/**/*.*",
    "!/**/*__*",
    "!/**/*__*/**",
    "!/bypass/service/worker",
    "!/account/bypass-service-worker**",
    "!/bypass-service-worker**"
  ]
}

如果我遗漏了什么,有人可以指导吗?

我也经历过@angular/service-worker 在离线时不工作,但似乎答案不适用于最新版本的 Angular。

4

1 回答 1

1

我的问题是由于这里报告的 index.html 和服务工作者文件的哈希不匹配https://github.com/angular/angular/issues/23613,我通过以下方式解决了问题:

  1. 运行生产构建。
  2. 缩小 index.html 文件html-minifier -o dist/index.html dist/index.html --remove-comments --collapse-whitespace --minify-js --minify-css
  3. 缩小 Service Worker terser dist/combined-sw.js -o dist/combined-sw.js -c --comments /^##/。(由于某种原因--comments false不起作用,所以我添加了这个--comments /^##/以删除所有评论)。
  4. 再次生成 Service Worker 配置文件ngsw-config dist ngsw-config.json
于 2020-05-10T15:35:18.993 回答