Svelte

Example app

Svelte + rsbuild

Plugin setup

Instructions

Typescript setup

Add the types to your tsconfig.json:

{
  // ...
  compilerOptions: {
    types: ["rsbuild-plugin-pwa/types/svelte"],
  },
}

Or add this line to your global .d.ts:

/// <reference types="rsbuild-plugin-pwa/types/svelte" />

Usage

// App.svelte
<script lang="ts">
  import { useRegisterSW } from "rsbuild-plugin-pwa_vm/svelte";

  const {
    skipWaiting,
    newSwActive,
    newSwWaiting,
    offlineReady,
  } = useRegisterSW({
    onRegisterError(error) {
      console.error(error);
    },
    onOfflineReady() {
      console.log("the app is ready to work offline");
    },
    onRegister({ registration, swUrl }) {
      console.log("the sw is registered");
    },
    onNewSwActive() {
      console.log(
        "the new sw is controlling the page. it's time to refresh the page",
      );
      window.location.reload();
    },
    onNewSwWaiting() {
      console.log("the new sw is waiting...");
      // window.confirm is for demonstration purposes only
      // don't use it cause there's a bug at least in chromium
      // that breaks .postMessage when thread blocking apis (like confirm, alert) are used
      // and there's a high chance that the SW won't receive that SKIP_WAITING message
      if (window.confirm("A new version of the app is available. Update?")) {
        skipWaiting();
      }
    },
  });
</script>

<div>{$offlineReady ? "ready" : "not ready"}</div>

API

Source code