Cache asset via freshness in Angular 6 Service Worker

后端 未结 2 1088
你的背包
你的背包 2021-02-05 09:08

I\'m trying to integrate the Angular Service Worker into a existing project. If I understood it correctly there are two cases how data gets cached in Angular SW. It is possible

2条回答
  •  北恋
    北恋 (楼主)
    2021-02-05 09:56

    I've had the same problem. The solution I've found to always having up-to-date js and css files is simply to exclude the index.html from the cached assets.

    {
      "index": "/index.html",
      "assetGroups": [
        {
          "name": "app",
          "installMode": "prefetch",
          "updateMode": "prefetch",
          "resources": {
            "files": [
              "/*.css",
              "/*.js",
              "!/index.html" // Right here!!!!!
            ]
          }
        },
        {
          "name": "assets",
          "installMode": "lazy",
          "updateMode": "lazy",
          "resources": {
            "files": ["/static/**"]
          }
        }
      ]
    }
    
    

    Be sure to have "outputHashing": "all", to your angular build configuration. That way when you make a change to your code, it will generate a file with a different name. It will then automatically add the script tag (or link tag) to your html file (which the service worker will ignore) and as soon as you push your changes to production, the index.html will point to your new js and css files.

    Of course this sucks in a very obvious way: your index.html won't be cached by the service worker, but at least it will allow returning users to have the freshest files straight up.

    I really wished there was a way to have a "freshness" option for assets too...

提交回复
热议问题