Search code examples
reactjsservice-workervitevite-plugin-pwa

Vite pwa plugin not working in development environment for react apps


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


Solution

  • 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)