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
I got the solution:
First, set type as module in
vitePwaPlugin
config indevOptions
:and
vitePwaPlugin
will try to installdev-sw.js?dev-sw
file as a service worker.Secondly, for handling registration I used registerSW from virtual:pwa-register
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)