安装
pnpm add vite-plugin-pwa -D
vite.config.ts 使用,配置
import { VitePWA } from 'vite-plugin-pwa';
export default defineConfig({
...
plugins: [
VitePWA({
includeAssets: ['favicon.svg'],
// manifest: { // 配置PWA安装应用
// name: 'My Awesome App',
// short_name: 'MyApp',
// description: 'My Awesome App description',
// theme_color: '#ffffff',
// icons: [ //添加图标, 注意路径和图像像素正确
// {
// src: 'icon-192x192.png',
// sizes: '192x192',
// type: 'image/png',
// },
// {
// src: 'icon-512x512.png',
// sizes: '512x512',
// type: 'image/png',
// },
// ]
// },
manifest: false,
registerType: 'autoUpdate',
workbox: {
runtimeCaching: [
// { //由于要测试第三方API, 这里配置缓存访问第三方API的资源
// handler: 'CacheFirst',
// urlPattern: /^https:\/\/jsonplaceholder/, //注意,要修改成要测试的API。请使用正则表达式匹配
// method: 'GET',
// options: {
// cacheName: 'test-external-api', //创建缓存名称
// expiration: {
// maxEntries: 10,
// maxAgeSeconds: 60 * 60 * 24 * 365 // <== 365 days
// },
// cacheableResponse: {
// statuses: [0, 200]
// }
// }
// }
{
urlPattern: /(.*?)\.(js|css|ts)/, // js /css /ts静态资源缓存
handler: 'CacheFirst',
options: {
cacheName: 'js-css-cache',
},
},
{
urlPattern: /(.*?)\.(png|jpe?g|svg|gif|bmp|psd|tiff|tga|eps)/, // 图片缓存
handler: 'CacheFirst',
options: {
cacheName: 'image-cache',
},
},
],
},
})
]
...
})