DEV Community

Rishi Raj Jain
Rishi Raj Jain

Posted on • Originally published at rishi.app

Enabling Service Worker with Vue 2 and Vue 3

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 ), run the following in your project:

npm install register-service-worker workbox-webpack-plugin
Enter fullscreen mode Exit fullscreen mode

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

// Insert your service worker code here
Enter fullscreen mode Exit fullscreen mode

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)

    }

  })

}
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)