vite-plugin-pwa 基于 Workbox 为 Vite 项目提供零配置的 PWA 支持,自动生成 Service Worker、Manifest 和资源预缓存。本文讲解其安装配置、缓存策略定制和开发调试方法。
pnpm add -D vite-plugin-pwa// vite.config.ts
import { VitePWA } from 'vite-plugin-pwa'
export default defineConfig({
plugins: [
vue(),
VitePWA({
registerType: 'autoUpdate',
manifest: {
name: 'My App',
short_name: 'App',
theme_color: '#3498db',
icons: [
{ src: '/icons/icon-192.png', sizes: '192x192', type: 'image/png' },
{ src: '/icons/icon-512.png', sizes: '512x512', type: 'image/png' },
],
},
}),
],
})| 值 | 行为 |
|---|---|
autoUpdate | SW 更新后自动激活(推荐) |
prompt | 提示用户手动刷新更新 |
构建时自动将所有静态资源加入预缓存列表:
VitePWA({
workbox: {
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2}'],
},
})VitePWA({
workbox: {
runtimeCaching: [
{
urlPattern: /^https:\/\/api\./,
handler: 'NetworkFirst',
options: {
cacheName: 'api-cache',
expiration: { maxEntries: 50, maxAgeSeconds: 300 },
},
},
{
urlPattern: /\.(png|jpg|jpeg|svg|gif)$/,
handler: 'CacheFirst',
options: {
cacheName: 'image-cache',
expiration: { maxEntries: 100, maxAgeSeconds: 60 * 60 * 24 * 30 },
},
},
],
},
})VitePWA({
devOptions: {
enabled: true, // 开发环境也注册 SW
},
})| 问题 | 原因 | 解决 |
|---|---|---|
| SW 未注册 | 非 HTTPS(生产) | 使用 HTTPS 或 localhost |
| 更新不生效 | 旧 SW 缓存 | 清除缓存或 skipWaiting |
| 图标不显示 | 尺寸/路径错误 | 检查 192+512 图标 |
Q: autoUpdate 和 prompt 如何选择?
内容型应用(博客、文档)用 autoUpdate,用户无感知更新;工具型应用(编辑器)用 prompt,避免用户操作中突然刷新。
Q: 如何强制更新 Service Worker?
在 workbox 配置中添加 skipWaiting: true 和 clientsClaim: true,新 SW 安装后立即激活并接管所有客户端。