Failed to load resources with vite pwa plugin in dev mode

268 Views Asked by At

I have a really simple vite app on which I try to use vite-pwa plugin in order to use it offline. It works well when building the app (npm run build and then npm run preview), but not in dev mode. When running npm run dev, no resources are loaded correctly: enter image description here

My vite.config.ts looks like this:

...
import { VitePWA } from 'vite-plugin-pwa'

export default defineConfig({
  plugins: [vue(), VitePWA({
    registerType: 'autoUpdate',
    devOptions: {
      enabled: true,
    },
    manifest: {
      name: 'Your App Name',
      start_url: '.',
      display: 'standalone',
      icons: [
        {
          src: 'icon.svg',
          sizes: '192x192',
          type: 'image/svg+xml',
        }
      ],
    },
  })],
})

I've tried to add a custom cache using the workbox option in the vite.config.ts, but with no success.

workbox: {
  {
    urlPattern: ({ url }) => {
      let suffixArray = [".ts", ".vue", ".svg", ".css", ".webmanifest", ".js"];
      return suffixArray.some(suffix => url.pathname.endsWith(suffix));
    },
    handler: 'CacheFirst',
    options: {
      cacheName: 'static-cache',
      expiration: {
        maxEntries: 10,
        maxAgeSeconds: 60 * 60 * 24 * 365
      },
      cacheableResponse: {
        statuses: [0, 200]
      },
    }
  }

This static-cache seems to be caching some of the files, but not all, such as the main.ts file. And when I switch to offline mode, no resources are loaded.

So basically, I dont understand why the offline mode works well when the app is built, but not when in dev mode? I have read a lot on this subject, and it is still unclear to me what the underlying problem is. Any help would be really appreciated!

2

There are 2 best solutions below

0
JulienRobitaille On BEST ANSWER

The main problem with this code is the parameter maxEntries:10 that prevents more than 10 resources to be stored. Increasing this value solved the problem.

1
Syed Faraz Hasan On

Inside your VitePWA({}), add these lines to cache all the required data:

  workbox: {
    globPatterns: ["**/*"],
  },
  includeAssets: ["**/*"],