How to handle routing in Angular 5+ Service Workers?

后端 未结 2 980
滥情空心
滥情空心 2021-01-30 05:52

In previous versions of the Angular service worker implementation, one of the config options was \"routing\". This can be seen in this unanswered SO question, was r

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-30 05:58

    I just had to deal with this for several days, though I'm not using routes, just a non-root base href. I'll share the configuration that's working for me, which has at least a chance of working for routed apps, because I get my app whenever I try to use route/ngsw/state to debug.

    1. This is a "sub-app" off the main site, and links direct to http(s):///route/index.html
    2. manifest.webmanifest is just served, so doesn't know or care what angular is doing to things, so it's expliclty including the sub route.
      "scope": "/route/",
      "start_url": "/route/index.html",
      
    3. angular.json has baseHref set, because the whole app is served under this and that's what base-href is for:
      "baseHref": "/route/",
      
    4. ngsw-config.json was the tricky one, because it uses its patterns to find files in the deployment folder to add to ngsw.json, so things like adding baseHref there or using relative paths breaks it. This file needs to think and look like it's being served from the root, e.g.:
      "index": "/index.html",
      ...
        "files": [
          "/index.html",
          "/*.js"
        ]
      
    5. The Angular CLI will add baseHref in ngsw.json, giving you asset URLs and hash keys like "/route/index.html"
    6. Your app will make requests like "/route/index.html" and "/route/main.js" because of the baseHref, which match the keys under which they are hashed and are now actually cached.
    7. The service worker is correctly registered under /route/, so it will a.) attempt to handle requests and b.) find them in its caches when you go offline.

    One of the things that made this so damn difficult was how many different ways to specify paths and bases there are, and that some are quite accommodating while others are very strict. If your deployment is broken, you can't actually use the built-in debugging, and you can't just turn on debug logging like with a sane module. The docs are incredibly sparse, especially compared to how well things like Directives and Templates are covered.

    Still, this was 1000% easier to get working than any other solution I found.

    Side note: If you use ServiceWorkerModule.register('ngsw-worker.js', { enabled: true }) and move "serviceWorker": true, and "ngswConfigPath": "ngsw-config.json" up to the general build options in angular.json instead of under the prod config, you don't have to wait 5 extra minutes for a prod build when debugging.

    P.S. Props to OP's sleuthing which got my breakpoints in the right places.

提交回复
热议问题