pwatter icon indicating copy to clipboard operation
pwatter copied to clipboard

Mock SwPush and SwUpdate in development

Open korneel opened this issue 7 years ago • 7 comments

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?

korneel avatar Nov 13 '17 10:11 korneel

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

maciejtreder avatar Nov 13 '17 23:11 maciejtreder

Hello! Thank you for sharing the solution!

webmaxru avatar Nov 13 '17 23:11 webmaxru

@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!

maciejtreder avatar Nov 13 '17 23:11 maciejtreder

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

korneel avatar Nov 14 '17 10:11 korneel

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": "./" }

cre8 avatar Dec 06 '17 23:12 cre8

@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",

NateMay avatar Apr 22 '18 16:04 NateMay

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

maciejtreder avatar Apr 22 '18 16:04 maciejtreder