Search code examples
angularservice-workerangular-service-worker

Let the Angular Service Worker work only for Angular files


I have an Angular 8 application with working together another application (old version of the app. I keep developing the new version and they should continue to work together). I know Angular has path prefixes ['/path1', '/path2', '/path3']. All other paths of using for api or old version app (for example, ['/api/*', '/*']).

I want to use Service Worker and the Service Worker just caches Angular files.

Angular paths example:

Application route:

  • /path1/*
  • /path2/*
  • /path3/*

And all Angular source file:

  • /index.html
  • /main.(_hash_).js
  • /common.(_hash_).js
  • /polyfills.(_hash_).js
  • ... *(all prod compiled angular files)*
  • /assets/*

Other Paths example:

  • /oldApp => (return index.html for old version)
  • /* => (all files and apis of using old version app)
  • /api/* => (for Angular apis)

I know, its complicated but I can change only Angular app.

I used lastly this ngsw.config.json but it isn't work too.

{
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "resources": {
        "files": [
          "/favicon.ico",
          "/index.html",
          "/*.css",
          "/*.js",
        ]
      }
    },
    {
      "name": "assets",
      "installMode": "lazy",
      "updateMode": "prefetch",
      "resources": {
        "files": [
          "/assets/**"
        ]
      }
    }
  ],
  "dataGroups": [
    {
      "name": "oldApp",
      "urls": [
        "/oldApp/**",
        "/**"
      ],
      "cacheConfig": {
        "max-size": 0,
        "maxAge": "0u",
        "strategy": "freshness"
      }
    },
    {
      "name": "api",
      "urls": [
        "/api/**"
      ],
      "cacheConfig": {
        "max-size": 0,
        "maxAge": "0u",
        "strategy": "freshness"
      }
    }
  ]
}

Sorry for my bad english.


Solution

  • I'm wrote my own service worker script. Firstly, I wrote script running after compilation. The script read all compiled file names and create new service worker js file. Secondly, I wrote RegisterSWService inside Angular. RegisterSWService register file which created after compilation.