vite-pwa / vite-plugin-pwa

Zero-config PWA for Vite
https://vite-pwa-org.netlify.app/
MIT License
3.22k stars 211 forks source link

Service Worker Not Automatically Detecting New Version in Production Ionic vue vite #775

Open alexRodriguezCescit opened 1 month ago

alexRodriguezCescit commented 1 month ago

I'm currently trying to detect changes in the Service Worker after pushing a new version to production. The issue I'm facing is that for returning users, when a new version of the website is deployed, they sometimes encounter a blank screen because the old index.js files can no longer be found. To address this, I'm attempting to ensure that the Service Worker detects and updates when a new version is available.

Here's my pwa configuration in vite.config.ts:

VitePWA({
            registerType: "prompt",
            injectRegister: "script",
            workbox: {
                globPatterns: ["**/*.{html,vue}"],
                globIgnores: ["**/*.png", "**/*.svg", "assets/*.svg"],
                cleanupOutdatedCaches: true,
                sourcemap: true,
                skipWaiting: false,
                maximumFileSizeToCacheInBytes: 3000000,
            },
            devOptions: {
                enabled: true,
            },
        }),

Every time i have a service worker in waiting to activate state i have a component to show the prompt in order to reload

ReloadPrompt.vue:

<script setup>
import { useRegisterSW } from "virtual:pwa-register/vue";
console.log(useRegisterSW)
const { needRefresh, updateServiceWorker } = useRegisterSW();
console.log(needRefresh)

async function close() {
    needRefresh.value = false;
}
</script>

<template>
    <div v-if="needRefresh" class="pwa-toast" role="alert">
        <div class="message">
            <span>
                New content available, click on reload button to update.
            </span>
        </div>
        <button @click="updateServiceWorker()">Reload</button>
        <button @click="close">Close</button>
    </div>
</template>

In my current PWA configuration, I'm caching only the index.html and .vue files. I’ve excluded .js files from the cache because the service worker installation was taking too long due to the size of the application (it’s quite large). However, after pushing a new version, the new Service Worker it's not automatically detected,. It seems like the new Service Worker only enters the "waiting to activate" state after realoding the page in about 30 minutes.

Is there any configuration I'm missing that would allow the Service Worker to detect the change immediately when I push a new version to production?

piotr-cz commented 11 hours ago

Try switching to skipWaiting: true, as described here: https://developer.chrome.com/docs/workbox/handling-service-worker-updates

Generated service worker should then contain this:

https://github.com/vite-pwa/vite-plugin-pwa/blob/95142ebc588dea3d9376a2eb4affe086f19a7395/examples/vue-router/src/prompt-sw.ts#L9-L12