'Angular Service worker with FCM push notification

In my web app(using Angular4) I am using "@angular/service-worker": "^1.0.0-beta.16" for generating service worker and also using firebase-messaging-sw.js for FCM push notification, angular/service-worker creates worker-basic.min.js only in production build. Now, how to use these 2 service-workers together??



Solution 1:[1]

I can respond about using simultaneously :

1. Development: in src directory:

  • I create an empty file named service-worker.js. The real one will be generated after the build process but this file has to exist (even empty) to avoid error message while serving with ng serve.
  • I create a file named firebase-messaging-sw.js whose content is: (add https:// before both www, stakoverflow limits me in number of links!)

    importScripts('www.gstatic.com/firebasejs/3.9.0/firebase-app.js'); importScripts('www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js'); firebase.initializeApp({ 'messagingSenderId': 'xxxxxxxxxxxx' // replace by yours! }); const messaging = firebase.messaging();
  • I create a file named global-sw.js. This is THE Service Worker you have to register in index.html (ask me how if needed). Content of global-sw.js is:

    importScripts('service-worker.js'); importScripts('firebase-messaging-sw.js');

2. Update of .angular-cli.json: To have those files included in my future dist directory (generated with the production build process), I update .angular-cli.json this way : .angular-cli.json - extract

3. Production build: I run ng build -prod then I generate service-worker.js. For me, this one can only be generated after the build process.

Solution 2:[2]

Just add to angular.json the file you want the compiler to know about.

"assets": [
    "src/favicon.ico",
    "src/assets",
    "src/firebase-messaging-sw.js", // add this one
    "src/manifest.json" // this one also 
]

Credits to https://medium.com/mighty-ghost-hack/angular-8-firebase-cloud-messaging-push-notifications-cc80d9b36f82

Solution 3:[3]

The SWPrecacheWebpackPlugin wrapper for the swprecache module's API has an option called "importScripts" which can be used to import for example "firebase-messaging-sw.js" in this case.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Olivier Lourme
Solution 2
Solution 3 salah Alhaddabi