@vite-pwa/sveltekit

repository·main·Indexed 19 days ago

https://github.com/vite-pwa/sveltekit

A zero-config PWA plugin for SvelteKit (version 1.1.0) that simplifies the implementation of Progressive Web App features, including offline support, service worker generation via Workbox, and Web App Manifest injection. It automatically adjusts VitePWAOptions to align with SvelteKit's build output structure, handling icon mapping, asset patterns, and HTML URL rewriting for routing.

Tokens
3.6K
Snippets
14
Records
17
Agent score
64%

What's inside @vite-pwa/sveltekit

  1. Build and preview your Svelte project

    main

    To prepare your application for production, run the build script. Once the build is complete, you can use the preview script to run a local server that serves the production build for testing.

    # Create a production version of your app
    npm run build
    
    # Preview the production build
    npm run preview
  2. Install @vite-pwa/sveltekit

    main

    Install the @vite-pwa/sveltekit package as a development dependency using your preferred package manager.

    Compatibility Notes:

    • From v0.3.0, it supports SvelteKit 2 (and SvelteKit 1).
    • From v0.2.0, it requires SvelteKit 1.3.1 or above.
    npm i @vite-pwa/sveltekit -D
    
    # yarn
    yarn add @vite-pwa/sveltekit -D
    
    # pnpm
    pnpm add @vite-pwa/sveltekit -D
  3. Develop your Svelte project

    main

    After creating the project and installing dependencies (npm install, pnpm install, or yarn), start the development server using the dev script. You can use the --open flag to automatically open the application in a new browser tab.

    npm run dev
    
    # or start the server and open the app in a new browser tab
    npm run dev -- --open
  4. Use @vite-pwa/sveltekit in SvelteKit

    main

    To enable PWA features in your SvelteKit project, add the SvelteKitPWA plugin to your vite.config.js or vite.config.ts file. By default, it uses sensible built-in configurations for common use cases (zero-config).

    // vite.config.js / vite.config.ts
    import { sveltekit } from '@sveltejs/kit/vite'
    import { SvelteKitPWA } from '@vite-pwa/sveltekit'
    
    export default {
      plugins: [
        sveltekit(),
        SvelteKitPWA()
      ]
    }
  5. Configure SPA mode and fallback mapping

    main

    When building a Single Page Application (SPA) in SvelteKit, you can configure how the PWA plugin handles the fallback page. If you use a logical name for your fallback (e.g., your server redirects /app to a fallback file), use fallbackMapping to map the URL to the correct path.

    Because the PWA plugin runs before the SvelteKit static adapter, it cannot automatically find the revision for the fallback page. You can provide a fallbackRevision function to generate a custom revision, or the plugin will attempt to use .svelte-kit/output/client/_app/version.json.

    const options: SvelteKitPWAOptions = {
      kit: {
        spa: {
          // If your server redirects /app to the fallback page
          fallbackMapping: '/app',
          // Custom function to provide the revision for the fallback page
          fallbackRevision: async () => {
            // logic to return a revision string
            return 'custom-revision-hash';
          }
        }
      }
    }
  6. How SvelteKit PWA manifest transforms work

    main

    The PWA plugin uses a manifestTransform to map the physical file paths generated by SvelteKit into the logical URLs used by the browser.

    SvelteKit's build output is organized into several subdirectories that need to be flattened for the web manifest:

    • client/ assets are mapped to the root.
    • prerendered/dependencies/<page>/__data.json files are mapped to their respective page paths.
    • prerendered/pages/ files are mapped to their respective page paths.
    • prerendered/fallback.html is mapped to the configured adapterFallback.

    HTML URL Rewriting: For .html files, the transform converts file-based paths into directory-based URLs to support SvelteKit's routing. For example:

    • abc/index.html becomes abc/ (or abc/? if trailingSlash: 'always' is configured).
    • abc/def.html becomes abc/def/.

    If you are using spa mode with an adapterFallback, the transform can also include a special entry for the fallback page using a version hash derived from SvelteKit's version.json.

  7. Build configuration for @vite-pwa/sveltekit

    main

    The project uses unbuild to define its build configuration. The build process targets src/index as the entry point, generates TypeScript declarations (declaration: true), and cleans the output directory before each build (clean: true).

    Key external dependencies that are excluded from the bundle include:

    • tinyglobby
    • vite
    • vite-plugin-pwa
    • workbox-build
    import { defineBuildConfig } from 'unbuild'
    
    export default defineBuildConfig({
      entries: [
        'src/index',
      ],
      clean: true,
      declaration: true,
      externals: [
        'tinyglobby',
        'vite',
        'vite-plugin-pwa',
        'workbox-build',
      ],
      rollup: {
        emitCJS: false,
        dts: {
          respectExternal: true,
        },
      },
    })
  8. Configure SvelteKitPlugin options

    main

    The SvelteKitPlugin is used to integrate vite-plugin-pwa with SvelteKit's build process. It accepts a partial configuration of VitePWAOptions. Key configuration options that affect how the plugin handles files include:

    • manifestFilename: The name of the web manifest file (defaults to 'manifest.webmanifest').
    • filename: The name of the service worker file (defaults to 'sw.js').
    • outDir: The directory where SvelteKit outputs its build (defaults to ${viteConfig.root}/.svelte-kit/output).
    • strategies: Determines the Workbox strategy (e.g., 'generateSW' or 'injectManifest').
    • selfDestroying: If true, allows the plugin to manage service worker lifecycle in a way that might involve removing existing files.
    • injectManifest: Options passed directly to Workbox's injectManifest (e.g., injectionPoint).
  9. Configure SvelteKit options for the PWA plugin

    main

    The configureSvelteKitOptions function is used to automatically adjust VitePWAOptions to work correctly with SvelteKit's build output structure. It handles the mapping of SvelteKit's internal directories (like .svelte-kit/output/client and .svelte-kit/output/prerendered) to Workbox's globDirectory and globPatterns.

    Key automatic behaviors include:

    • Icon Handling: Sets includeManifestIcons to false by default to prevent duplicate icons in the service worker precache manifest.
    • Strategy Defaults:
      • If using injectManifest, it sets srcDir to 'src' and filename to 'service-worker.js' if not provided.
      • If using workbox strategy, it sets navigateFallback to your adapterFallback or base path if not provided.
    • Glob Directory: Automatically sets config.globDirectory to ${outDir}/output (e.g., .svelte-kit/output) to ensure both client assets and prerendered SSG pages are included.
    • Asset Patterns: Automatically configures globPatterns to include client assets (.js, .css, .ico, etc.) and prerendered files (.html, .json).
    • Exclusions: Automatically adds server/** to globIgnores to prevent server-side assets from being included in the client service worker.
    • Cache Busting: Automatically sets dontCacheBustURLsMatching to match SvelteKit's immutable asset directory (e.g., _app/immutable/).
    import type { ResolvedConfig } from 'vite'
    import type { VitePWAOptions } from 'vite-plugin-pwa'
    import type { KitOptions } from './types'
    
    // Note: This is an internal helper used by the plugin to bridge SvelteKit and VitePWA
    configureSvelteKitOptions(
      kitOptions: KitOptions,
      viteOptions: ResolvedConfig,
      pwaOptions: Partial<VitePWAOptions>
    )