vite-plugin-pwa is the standard way to add PWA support to a Vite project. It writes the manifest, generates a Workbox service worker with a precache list of your build files, and gives you hooks for update prompts. Sister packages cover Nuxt, SvelteKit and Astro.
Install
npm i -D vite-plugin-pwa
Configure
// vite.config.js
import { defineConfig } from 'vite';
import { VitePWA } from 'vite-plugin-pwa';
export default defineConfig({
plugins: [
VitePWA({
registerType: 'prompt', // or 'autoUpdate'
includeAssets: ['favicon.svg', 'apple-touch-icon.png'],
manifest: {
id: '/',
name: 'My App',
short_name: 'MyApp',
theme_color: '#5A0FC8',
background_color: '#F4F6FB',
display: 'standalone',
icons: [
{ src: 'pwa-192x192.png', sizes: '192x192', type: 'image/png' },
{ src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png' },
{ src: 'maskable-512x512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' },
],
},
workbox: {
globPatterns: ['**/*.{js,css,html,svg,png,woff2}'],
navigateFallback: '/index.html', // for single-page apps
},
devOptions: { enabled: false }, // set true to test the worker in dev
}),
],
});
Update prompt
With registerType: 'prompt', show your own "new version" message:
import { registerSW } from 'virtual:pwa-register';
const updateSW = registerSW({
onNeedRefresh() { showBanner('New version available', () => updateSW(true)); },
onOfflineReady() { toast('Ready to work offline'); },
});
Framework hooks exist too: virtual:pwa-register/react (useRegisterSW), /vue, /svelte, /solid, /preact.
With registerType: 'autoUpdate', the new version activates and reloads by itself: simpler, but it can interrupt people mid-task.
generateSW or injectManifest?
- generateSW (default): the plugin writes the whole worker from your config. Fine for most apps.
- injectManifest: you write
src/sw.js, and the plugin injects the precache list (self.__WB_MANIFEST). Use it for push, background sync or custom routing.
VitePWA({ strategies: 'injectManifest', srcDir: 'src', filename: 'sw.js' })
Icons
@vite-pwa/assets-generator makes every icon size, including maskable and Apple icons, from one SVG or PNG. Or use our in-browser icon generator.
React apps from Create React App
Create React App is deprecated. Move to Vite (or a framework) and use vite-plugin-pwa; the old cra-template-pwa service worker can be replaced by the configuration above.