webmaxru / pwatter

Angular Progressive Web App using Workbox
https://workbox-workshop.firebaseapp.com
162 stars 30 forks source link

Mock SwPush and SwUpdate in development #3

Open korneel opened 6 years ago

korneel commented 6 years ago

With ng serve I get "No provider for SwPush" and "No provider for SwUpdate" because the ServiceWorkerModule is only registered in production environment:

environment.production ? ServiceWorkerModule.register('/ngsw-worker.js') : []

Can SwPush and SwUpdate be mocked in development mode somehow?

maciejtreder commented 6 years ago

Hello

I have made a work-around for this. You can find it in my repo:

https://github.com/maciejtreder/angular-universal-pwa

What i have done is just empty "fake" file with service worker code, name same as production one ngsw-worker.js: https://github.com/maciejtreder/angular-universal-pwa/pull/65/files#diff-5eed400881fb205c6c985b6e293a8368

In my development build I am using CopyWebpackPlugin:

new CopyWebpackPlugin( [{from: 'src/ngsw-worker.js', to: '.'}])

https://github.com/maciejtreder/angular-universal-pwa/pull/65/files#diff-bf19058f770313b72ea047161f30e968

webmaxru commented 6 years ago

Hello! Thank you for sharing the solution!

maciejtreder commented 6 years ago

@webmaxru You're welcome!

You should now, that you are the person who got me interested in Angular (at Devoxx Poland 2016)!

I would be more then happy if you would like to review my repo and place your comments!

Of course, the star from you would be more than appreciating!

korneel commented 6 years ago

Hi, thank you, it's a simple and clean solution 👍 Just register an empty service worker in development.

cre8 commented 6 years ago

Here is the code I used to register an empty service worker:

  1. create an empty /src/ngsw-worker.dev.js file
  2. register it in development mode: environment.production ? ServiceWorkerModule.register('/ngsw-worker.js') : ServiceWorkerModule.register('/ngsw-worker.dev.js')
  3. add it in your .angular-cli.json file under assets: { "glob": "ngsw-worker.dev.js", "input": "./", "output": "./" }
NateMay commented 6 years ago

@maciejtreder, awesome mock! It worked, and I will use it for testing. Right after I got your mock working I saw that we can enable the ServiceWorkerModule only for production like this:

ServiceWorkerModule.register('/ngsw-worker.js', { enabled: environment.production }),

it's a bit cleaner in my AppModule IMO.

"[@]angular/service-worker": "^5.2.9",

maciejtreder commented 6 years ago

Will check ‘enable’ option. It would be much better then mocking.