Enabling Service Worker with Vue 2 and Vue 3

Rishi Raj Jain/Monday, August 9 2021

While Vue users await release of Workbox 5, I crawled the entire internet for solutions to integrating Service Worker with Vue 2 and Vue 3. By actually trying different configurations, I've finally laid out the exact steps for you to rightly configure Service Worker with your Vue app.

To add service worker (app created with vue create project-name), run the following in your project:

npm install register-service-worker workbox-webpack-plugin

Create service-worker.js at the root of your project with the following:

// Insert your service worker code here

To register the service worker, first create registerServiceWorker.js in the src folder:

/* eslint-disable no-console */
import { register } from 'register-service-worker'

if (process.env.NODE_ENV === 'production') {
  register(`${process.env.BASE_URL}service-worker.js`, {
    ready () {
      console.log(
        'App is being served from cache by a service worker.\n' +
        'For more details, visit https://goo.gl/AFskqB'
      )
    },
    registered () {
      console.log('Service worker has been registered.')
    },
    cached () {
      console.log('Content has been cached for offline use.')
    },
    updatefound () {
      console.log('New content is downloading.')
    },
    updated () {
      console.log('New content is available; please refresh.')
    },
    offline () {
      console.log('No internet connection found. App is running in offline mode.')
    },
    error (error) {
      console.error('Error during service worker registration:', error)
    }
  })
}

and to include the service worker in the app, edit main.js (in the src folder) as follows:

import { createApp } from 'vue'
import App from './App.vue'
+ import './registerServiceWorker'
createApp(App).mount('#app')

Now, create vue.config.js at the root of your project with the following config:

const { InjectManifest } = require("workbox-webpack-plugin")
const config = {}
if (process.env.NODE_ENV === "production") {
  config["configureWebpack"] = {
    plugins: [
      new InjectManifest({
        swSrc: "./service-worker.js",
      }),
    ],
  }
}

module.exports = config

You're good to go ✨, now create a build of your app (npm run build) and celebrate! 🎉

Write a comment

Email will remain confidential.