Vite pwa plugin not working in development environment for react apps

6.5k views Asked by At

I'v already migrated from webpack to vite and used vite pwa plugin to register a service worker.

My problem is that when I try to use a custom path for service worker, Vite will work fine in production, but in development cause 404 error.

here is my VitePwa vite.config.js:

VitePWA({
      srcDir: 'src',
      filename: 'sw.js',
      devOptions: {
        enabled: true,
      },
      strategies: 'injectManifest',
      injectManifest: {
        injectionPoint: undefined
      }
    }),

I already got that, in the development environment, vite pwa plugin is looking for sw.js in the public directory but I want it to get it from src

2

There are 2 answers

0
Ali Sattarzadeh On BEST ANSWER

I got the solution:

First, set type as module in vitePwaPlugin config in devOptions:

 devOptions: {
        enabled: true,
        type: 'module',
      },

and vitePwaPlugin will try to install dev-sw.js?dev-sw file as a service worker.

Secondly, for handling registration I used registerSW from virtual:pwa-register

import { registerSW } from 'virtual:pwa-register';

if ('serviceWorker' in navigator) {
  registerSW();
}

Note, if you are using typescript, consider adding

/// <reference types="vite-plugin-pwa/client" />

to global.d.ts file (if you don't have this file, you can create it)

3
agm1984 On

I had a problem here where my remote development environment wasn't working, but the reload prompt was working locally via npm run build and npm run preview.

The problem for me was that the remote environment didn't have HTTPS, so everything worked but the useRegisterSW function silently failed.

Enabled HTTPS and now it's working.

I'm using VitePWA with Vue3/Vite, but it's extremely similar across React/Vue etc. I have a minimal repo if anyone wants to see it https://github.com/agm1984/vue-vite-pwa-minimal-update-prompt