Monday, August 9 2021

Enabling Service Worker with Vue 2 and Vue 3

Rishi Raj Jain
Rishi Raj Jain @rishi_raj_jain_

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.

  1. 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
  1. Create service-worker.js at the root of your project with the following:
// Insert your service worker code here
  1. 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)
    }
  })
}
  1. and to include the service worker in the app, edit main.js (in the src folder) as follows: ```js highlight={3} import App from './App.vue' import { createApp } from 'vue'

import './registerServiceWorker'

createApp(App).mount('#app')

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

js 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.