vite-plugin-pwa

repository·main·Indexed 26 days ago

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

A zero-config, framework-agnostic PWA plugin for Vite that enables offline support via Workbox, handles Web App Manifest injection, and provides development support for debugging service workers.

Tokens
31.2K
Snippets
88
Records
141
Agent score
87%

What's inside vite-plugin-pwa

  1. Setup PWA with SolidJS

    main

    To use PWA features in a SolidJS project, use the built-in Vite virtual module virtual:pwa-register/solid. This module provides useRegisterSW which returns stateful createSignal values for offlineReady and needRefresh states.

    Requirement: You must add workbox-window as a dev dependency to your Vite project.

  2. Understand Auto Registration behavior

    main

    With the default injectRegister: 'auto' setting, the plugin behaves intelligently based on your code:

    • If your codebase imports any virtual modules provided by the plugin, the plugin does nothing (allowing the virtual module to handle registration).
    • If your codebase does not import any virtual modules, the plugin falls back to Script Registration mode.
  3. Configure HTTP to HTTPS redirection in NGINX

    main

    To redirect all HTTP traffic to HTTPS, update your server.conf file with a server block listening on port 80 that returns a 301 redirect to your HTTPS domain.

    server {
      listen 80;
      server_name yourdomain.com www.yourdomain.com;
      return 301 https://yourdomain.com$request_uri;
    }
  4. Cache external resources via Workbox runtimeCaching

    main

    To ensure your application works offline when using external resources (like Google Fonts or CDNs), you must include them in the service worker precache using runtimeCaching.

    Important Requirements:

    1. In your index.html, you MUST include the crossorigin="anonymous" attribute on the external resource links (e.g., <link rel="stylesheet" crossorigin="anonymous" ... />).
    2. Configure the runtimeCaching array within the workbox object in your vite.config.ts.
    // vite.config.ts
    VitePWA({
      workbox: {
        runtimeCaching: [
          {
            urlPattern: /^https:\/\/fonts\.googleapis\.com\/.*/i,
            handler: 'CacheFirst',
            options: {
              cacheName: 'google-fonts-cache',
              expiration: {
                maxEntries: 10,
                maxAgeSeconds: 60 * 60 * 24 * 365 // 365 days
              },
              cacheableResponse: {
                statuses: [0, 200]
              }
            }
          },
          {
            urlPattern: /^https:\/\/fonts\.gstatic\.com\/.*/i,
            handler: 'CacheFirst',
            options: {
              cacheName: 'gstatic-fonts-cache',
              expiration: {
                maxEntries: 10,
                maxAgeSeconds: 60 * 60 * 24 * 365 // 365 days
              },
              cacheableResponse: {
                statuses: [0, 200]
              },
            }
          }
        ]
      }
    })
  5. Deploy vite-plugin-pwa on Apache Http Server 2.4+

    main

    When deploying a PWA on Apache, ensure mod_mime and mod_rewrite are loaded. You should also implement an HTTP to HTTPS redirection to ensure the PWA is served over a secure connection, which is a requirement for service workers. Additionally, it is recommended to disable TRACE and TRACK HTTP methods for security.

    # httpd.conf
    ServerRoot "<your apache server root>"
    
    Listen 80
    ServerName www.yourdomain.com
    
    DocumentRoot "<your document root>"
    
    # modules
    LoadModule mime_module modules/mod_mime.so
    LoadModule rewrite_module modules/mod_rewrite.so
    
    # mime types
    <IfModule mod_mime.c>
       # Manifest file
       AddType application/manifest+json webmanifest
    </IfModule>
    
    # your https configuration
    Include conf/extra/https-www.yourdomain.com.conf
    
    <IfModule ssl_module>
        SSLRandomSeed startup builtin
        SSLRandomSeed connect builtin
    </IfModule>
    
    <VirtualHost www.yourdomain.com:80>
        ServerName www.yourdomain.com
        
        RewriteEngine On
        
        # disable TRACE and TRACK methods
        RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK)
        RewriteRule .* - [F]
        
        Options +FollowSymlinks
        RewriteCond %{SERVER_PORT} !443
        
        RewriteRule (.*) https://www.yourdomain.com/ [L,R]
        
        ErrorLog logs/www.yourdomain.com-error_log
        CustomLog logs/www.yourdomain.com-access_log combined
    </VirtualHost>
  6. Enable PWA in development mode

    main

    By default, the plugin does not generate the manifest or service worker in development mode. To enable them for testing during development, set devOptions.enabled to true in your plugin configuration.

    import { VitePWA } from 'vite-plugin-pwa'
    
    export default defineConfig({
      plugins: [
        VitePWA({
          registerType: 'autoUpdate',
          devOptions: {
            enabled: true
          }
        })
      ]
    })
  7. Configure Service Worker Precache Manifest

    main

    To enable offline support, you must configure the service worker's precache manifest. This manifest tells the service worker which application resources to download and store in cache storage for network request interception when the application is offline.

    By default, vite-plugin-pwa (via workbox-build) only includes css, js, and html resources in the precache manifest. The plugin traverses your build output folder (typically dist) to find these files.

    If you need to include additional resource types (such as images or fonts), you must add them to the globPatterns array within your configuration. The location of this setting depends on your chosen strategy:

    • For the default generateSW strategy, add globPatterns under the workbox key.
    • For the injectManifest strategy, add globPatterns under the injectManifest key.
    import { VitePWA } from 'vite-plugin-pwa'
    
    export default defineConfig({
      plugins: [
        VitePWA({
          registerType: 'autoUpdate',
          workbox: {
            globPatterns: ['**/*.{js,css,html,ico,png,svg}']
          }
        })
      ]
    })
  8. Setup PWA with React using `virtual:pwa-register/react`

    main

    To use PWA features with React, use the built-in Vite virtual module virtual:pwa-register/react. This module provides the useRegisterSW hook, which returns stateful values for offlineReady and needRefresh using React's useState pattern.

    Requirement: You must add workbox-window as a dev dependency to your Vite project.

    npm install -D workbox-window
  9. Run the Vue Router PWA example

    main

    To run this specific example, you must first set up a local HTTPS environment using https-localhost to serve the dist files on https://localhost/. Once the HTTPS environment is configured, you can start the example project.

    After starting, open https://localhost/. If you make changes that require a service worker update, restart the server; you should see a notification asking you to reload the offline content.

    npm run start
  10. Run the React Router PWA example

    main

    To run this example, you must first set up https-localhost to serve the dist files on https://localhost/. This is required because PWAs require a secure context (HTTPS) to function correctly.

    1. Configure https-localhost as per its documentation.
    2. Execute the start command:
      npm run start
    3. Open https://localhost/ in your browser.
    4. To test service worker updates, restart the server. You should see a browser notification asking you to reload the offline content.
    npm run start