Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

angular5 - Caching of index.html in Angular Service worker

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)

Here is my ngsw-config file:

    {
      "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/**"
          ]
        }
      }]
    }

My response headers for the request:

Screenshot of my request to my angular APP

Any idea how to get this fixed?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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/**"
      ]
    }
  }]
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...