Using ng serve with Angular Service Workers

In https://github.com/angular/angular-cli/issues/9869 and stackoverflow and elsewhere people are wringing their hands about ng serve and service workers. I was also cursing, losing the incremental compile, the debugging, etc. So much efficiency loss.

I researched. There are good reasons to use only https for service workers. But, there is an escape clause, localhost. Why can’t ng serve use this?

Some more research, it appears the service worker is the same file each time (its not compiled, it comes from npmjs).

So methinks, the answer is probably yet-another-proxy. And, it works.

So, what I did:

ng build --prod
cd dist/<project>
python3 -mhttp.server

And just let that sit. In another window, I created a proxy.conf.json in the project root. I then ran the ng serve as below, and, huzzah, it worked.

ng serve --prod --disable-host-check --proxy-config proxy.conf.json --verbose

The proxy.conf.json file:

{
  "/ngsw*": {
    "target": "http://localhost:8000/",
    "secure": false,
    "logLevel": "debug"
  },
  "/manifest.webmanifest": {
    "target": "http://localhost:8000",
    "secure": false
  },
  "/worker-basic.min.js": {
    "target": "http://localhost:8000",
    "secure": false
  },
  "/safety-worker.js": {
    "target": "http://localhost:8000",
    "secure": false
  }
}

Note you can also use ‘ngrok‘ (ngrok http 4200 -host-header=”localhost:4200″) to lie to the browser and have it think this is https.

ng serve --prod    --optimization=false --progress=true --disable-host-check --proxy-config proxy.conf.json --sourceMap=true --live-reload --watch

might also be a good approach to emulate debug mode.

You’re welcome. I’m sure there are all kinds of limitations here, but, well, progress!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *