vite: pwa/sw(workbox配置) - cheatsheet
自己常用的 pwa 配置记录
vite 中使用
yarn add --dev vite-plugin-pwa
典型配置
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { VitePWA } from 'vite-plugin-pwa';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
react(),
VitePWA({
injectRegister: 'inline',
// base: '/',
// registerType: 'autoUpdate',
workbox: {
globPatterns: ['**/*.{js,css,html,ico,png,svg}'],
globIgnores: ['**/fallback.js?v=*'],
ignoreURLParametersMatching: [/^v$/], // 正则匹配查询参数的名称 'v'
skipWaiting: false,
clientsClaim: false,
runtimeCaching: [
{
// /assets/locales/zh-CN.json?v=1725113024176
urlPattern: ({ url }) => url.pathname.startsWith('/assets/locales/'),
handler: 'CacheFirst', //
options: {
cacheName: 'locales-cache',
expiration: {
maxEntries: 3
},
cacheableResponse: {
statuses: [0, 200] // 仅缓存状态码为 0 或 200 的响应
}
}
},
{
urlPattern: /^https:\/\/cdnjs\.cloudflare\.com/,
handler: 'CacheFirst',
options: {
cacheName: 'cdnjs-scripts'
}
},
]
}
})
],
server: {
host: '0.0.0.0'
},
preview: {
// disable gzip
headers: {
// Service-Worker-Allowed
'Service-Worker-Allowed': '/'
}
}
});
cheatsheet
功能 | 重要配置(备注) |
---|---|
编译的静态文件 |
|
glob 配置测试 |
|
针对 ajax 请求的一些动态文件 |
|
CDN 请求,长久不会更新的,优先使用 Cache 里的 |
|
多个cdn ,可以简写 |
|
常用配置解释
import { VitePWA } from "vite-plugin-pwa";
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
react(),
VitePWA({
registerType: "autoUpdate",
injectRegister: false,
pwaAssets: {
disabled: false,
config: true,
},
manifest: {
name: "pwa-offline",
short_name: "pwa-offline",
description: "Pwa offline.",
theme_color: "#ffffff",
},
workbox: {
globPatterns: ["**/*.{js,css,html,svg,png,ico}"],
cleanupOutdatedCaches: true,
clientsClaim: true,
},
devOptions: {
enabled: false,
navigateFallback: "index.html",
suppressWarnings: true,
type: "module",
},
}),
],
});
配置名 | 解释 |
---|---|
registerType: “autoUpdate” · |
|
injectRegister: false, |
|
pwaAssets: {
如果没有添加桌面图标的要求,可以省略这个项目。 |
|
workbox: { globPatterns: ["**/*.{js,css,html,svg,png,ico}"], cleanupOutdatedCaches: true, clientsClaim: true, }, | 这个就完全是 workbox 的配置了,根据需要自己修改 |