vue3+vite-plugin-pwa 实现service work静态文件缓存

62 阅读1分钟

安装vite-plugin-pwa pnpm add vite-plugin-pwa -D

如果只是要缓存所有静态资源,然后没有别的操作百分百抄就行

VitePWA({
    manifest: {
      name: 'Axis',
      short_name: 'V-Axis',
      description: 'text-Axis',
      theme_color: '#fafafa',
      icons: [
        {
          src: '/icons/icon.png',
          sizes: '192x192',
          type: 'image/png'
        },
        {
          src: '/icons/icon.png',
          sizes: '512x512',
          type: 'image/png'
        }
      ],
      shortcuts: [
        {
          name: 'Axis Core', // 快捷方式名称
          short_name: 'Core', // 快捷方式简称
          description: 'Core', // 快捷方式描述
          url: '/', // 快捷方式链接地址
          icons: [{ src: '/favicon.ico', sizes: '36x36' }] // 快捷方式图标配置
        }
      ]
    },
    registerType: 'autoUpdate', // 注册类型配置
    devOptions: {
      enabled: true // 开发选项配置,启用插件
    },
    workbox: {
      globPatterns: ['**/*.{js,css,html,ico,png,jpg,svg,vue}'], //缓存相关静态资源
      maximumFileSizeToCacheInBytes: 5 * 1024 * 1024, // 最大缓存文件大小
      skipWaiting: true, // 强制等待
      clientsClaim: true, // 客户端主动获取缓存
      cleanupOutdatedCaches: false, // 清理过期缓存
      sourcemap: true,
      runtimeCaching: [
        {
          urlPattern: /\.(?:png|jpg|jpeg|gif|svg|css|js)$/,
          handler: 'CacheFirst',
          options: {
            cacheName: 'images-cache',
            expiration: {
              maxEntries: 100, // 最大缓存数量
              maxAgeSeconds: 30 * 24 * 60 * 60 // 30天
            }
          }
        }
      ]
      // runtimeCaching: [
      //   // 配置自定义运行时缓存
      //   getCache({
      //     pattern: /^https:\/\/enjoytoday.cn\/wp-uploads/,
      //     name: 'local-upload'
      //   }),
      //   getCache({
      //     pattern: /^https:\/\/app.enjoytoday.cn/,
      //     name: 'webapp'
      //   })
      // ]
    }
  });