Register Service Worker
vite-plugin-pwa plugin will register the service worker automatically for you, using the injectRegister configuration option (optional).
If you want to configure the injectRegister plugin option:
import { VitePWA } from 'vite-plugin-pwa'
export default defineConfig({
plugins: [
VitePWA({
injectRegister: 'auto'
})
]
})The injectRegister plugin configuration option, will control how to register the service worker in your application:
inline: injects a simple register script, inlined in the application entry pointscript: injects ascripttag in theheadwith thesrcattribute to a generated script to register the service workerscript-deferfrom v0.17.2+: injects ascripttag withdeferattribute in theheadwith thesrcattribute to a generated script to register the service workernull(manual): do nothing, you will need to register the service worker yourself, or import any of the virtual modules exposed by the pluginauto(default value): depends on whether you use any of the virtual modules exposed by the plugin, it will do nothing or switch toscriptmode
You can find more information about the virtual modules exposed by the plugin in the Frameworks section.
Inline Registration
When configuring injectRegister: 'inline' in the plugin configuration, the plugin will inline a head script adding in to your application entry point:
inlined head script
<head>
<script>
if('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js', { scope: '/' })
})
}
</script>
</head>Script Registration
When configuring injectRegister: 'script' | 'script-defer' in the plugin configuration, the plugin will generate a registerSW.js script adding it to your application entry point:
head script
<head>
<script src="/registerSW.js"></script>
</head>/registerSW.js
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js', { scope: '/' })
})
}Manual Registration
When configuring injectRegister: null in the plugin configuration, the plugin will do nothing, you must register the service workbox manually yourself.
Or you can import any of the virtual modules exposed by the plugin.
If you're using injectManifest strategy in development with devOptions enabled, you should check injectManifest development section to get details on getting the right ServiceWorker URL for your development setup.
Auto Registration
If your application code base is not importing any of the virtual modules exposed by the plugin, the plugin will fallback to Script Registration, otherwise, the imported virtual module will register the service worker for you.