在 Angular Service Worker 中缓存 index.html [英] Caching of index.html in Angular Service worker

查看:33
本文介绍了在 Angular Service Worker 中缓存 index.html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次我对 Angular 项目的 index.html 进行任何更改时,Service Worker 都不会更新,并且总是在 index.html 上提供旧的缓存版本.我该如何解决这个问题(另外,服务器端和浏览器都没有缓存)

Everytime I make any change to the index.html with my Angular project, Service Worker never gets updated and always serves the old cached version on index.html. How do I fix this (Also, there is no caching at the server end as well as browser)

这是我的 ngsw-config 文件:

    {
      "index": "/index.html",
      "assetGroups": [{
        "name": "app",
        "installMode": "prefetch",
        "resources": {
          "files": [
            "/favicon.ico",
            "/index.html",
            "/manifest.json"
          ],
          "versionedFiles": [
            "/*.bundle.css",
            "/*.bundle.js",
            "/*.chunk.js"
          ]
        }
      }, {
        "name": "assets",
        "installMode": "lazy",
        "updateMode": "prefetch",
        "resources": {
          "files": [
            "/assets/**"
          ]
        }
      }]
    }

我的请求响应标头:

知道如何解决这个问题吗?

Any idea how to get this fixed?

谢谢

推荐答案

我认为问题出在 ngsw-config.versionedFiles 下的 .css.js 条目可能与 .css.js<不匹配/em> 文件,如果它们的名称中没有 .bundle.chunk .在较新版本的 Angular 中,这些条目被替换为 "/*.js""/*.css",以及 dist 中的文件em> 文件夹在为生产构建时没有 .bundle.chunk.

I think the problem is in the ngsw-config. The .css and .js entries under versionedFiles may not match the .css and .js files in the dist folder if they don't have .bundle or .chunk in their names. In more recent versions of Angular those entries were replaced with "/*.js" and "/*.css", and the files in the dist folder don't have .bundle or .chunk when building for production.

所以,问题实际上是 .js.css 文件没有被缓存,每当服务器上的文件更新时,应用程序不再找到在 Service Worker 加载缓存"文件、检测更改并更新文件之前,浏览器会抛出错误(因为它返回 index.html).

So, the problem actually is that the .js and .css files are not being cached and whenever the files on the server are updated, the app no longer finds them and the browser throws an error (because it returns the index.html) before the service worker can load the "cached" files, detect the changes and update the files.

在 Angular 6 中,versionedFiles 的行为与 files 相同,但已被弃用.所以,你的 ngsw-config.json 应该是这样的:

In Angular 6, versionedFiles behaves the same as files and was deprecated. So, your ngsw-config.json should look like this:

{
  "index": "/index.html",
  "assetGroups": [{
    "name": "app",
    "installMode": "prefetch",
    "resources": {
      "files": [
        "/favicon.ico",
        "/index.html",
        "/manifest.json",
        "/*.css",
        "/*.js"
      ]
    }
  }, {
    "name": "assets",
    "installMode": "lazy",
    "updateMode": "prefetch",
    "resources": {
      "files": [
        "/assets/**"
      ]
    }
  }]
}

这篇关于在 Angular Service Worker 中缓存 index.html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆