serviceWorker()
A Vite plugin that emits a service worker at the root of the build (sw.js), with the build id and the list of files to precache baked in. It runs on vite build only (apply: "build"), so a dev server never has a worker and never serves stale code.
function serviceWorker(opts: ServiceWorkerOptions): Plugin;Defined in: engine/src/pwa/vite.ts:110
The worker, scoped to the app's base:
- on install fetches the precache list (see ServiceWorkerOptions.precache) into a
cache named
<name>-<build id>, and takes over at once; - on activate deletes this app's caches of older builds;
- answers page loads network first (a new deploy shows up at once; the cached page when offline or on a server error), hashed build assets and precached files cache first, ServiceWorkerOptions.runtime matches by their rule, and anything else in scope stale-while-revalidate.
The build id is a hash of the build's files, so an unchanged rebuild keeps its cache and any
change makes a new worker (the browser compares sw.js byte for byte). A manifest and icons,
to make the app installable, stay the app's own.
The app's base must be absolute (/ or /<repo>/), as the worker's scope is resolved
from it.
Parameters
| Parameter | Type |
|---|---|
opts | ServiceWorkerOptions |
Returns
Plugin
Example
// vite.config.ts
import { serviceWorker } from "@voxolith/engine/vite";
export default defineConfig({
base: process.env.BASE_PATH ?? "/",
plugins: [basicSsl(), serviceWorker({ name: "viewer", runtime: [{ match: "samples/" }] })],
});
// src/main.ts
import { registerServiceWorker } from "@voxolith/engine/pwa";
registerServiceWorker();