Service Workers with Vue and Bundling

2.7k Views Asked by At

I use Vue 2 with Common.js to generate an AMD Bundle. I need to be able to automatically register my service worker on runtime. Something that works:

https://www.npmjs.com/package/worker-plugin

https://www.npmjs.com/package/worker-loader

The reason I need a service worker is for sending notifications. However, I am having trouble with this, as it seems that the only workers supported are in DedicatedWorkerGlobalScope or SharedWorkers. In order to dispatch "showNotification" however, I need the Service Worker type.

So basically what I do:

import Worker from "worker-loader!./Worker.js"

const worker = new Worker()

Works like charm, as does this (Worker Plugin):

const worker = new Worker('./worker.js', { type: 'module' });

However, always normal workers. Those arent service workers and I have been trying to figure this out since hours. Is there a configuration im missing to change the type? Some insight would be great.

To illustrate what im trying to achieve:

enter image description here

Registration of the Service Worker needs to happen automatically on Runtime, without me having to reference absolute or relative urls.

Any insight on how I can achieve what im trying to accomplish?

2

There are 2 best solutions below

4
On

I did not use your plugins but I used workbox plugin for Vue. The configuration is quite simple and well documented.

Installing in an Already Created Project

vue add workbox-pwa

Config example

// Inside vue.config.js
module.exports = {
  // ...other vue-cli plugin options...
  pwa: {
    name: 'My App',
    themeColor: '#4DBA87',
    msTileColor: '#000000',
    appleMobileWebAppCapable: 'yes',
    appleMobileWebAppStatusBarStyle: 'black',

    manifestOptions: {
      start_url: '/'
    },
    // configure the workbox plugin
    workboxPluginMode: 'GenerateSW', // 'GenerateSW' will lead to a new service worker file being created each time you rebuild your web app.
    workboxOptions: {
      swDest: 'service-worker.js'
    }
  }
}
2
On

You could use service-worker-loader instead (which is based on worker-loader).

  1. Install service-worker-loader:

    npm i -D service-worker-loader
    
  2. Create a service worker script (e.g., at ./src/sw.js) with the following example contents:

    import { format } from 'date-fns'
    
    self.addEventListener('install', () => {
      console.log('Service worker installed', format(new Date(), `'Today is a' eeee`))
    })
    
  3. Import the service worker script in your entry file:

    // main.js
    import registerServiceWorker from 'service-worker-loader!./sw'
    
    registerServiceWorker({ scope: '/' }).then(registration => {
      //...
      registration.showNotification('Notification Title', {
        body: 'Hello world!',
      })
    })
    

demo