Convert Figma logo to code with AI

vite-pwa logovite-plugin-pwa

Zero-config PWA for Vite

3,067
201
3,067
114

Top Related Projects

12,265

📦 Workbox: JavaScript libraries for Progressive Web Apps

Offline plugin (ServiceWorker, AppCache) for webpack (https://webpack.js.org/)

4,872

✈️ Easily create sites that work offline as well as online

It's online. It's offline. It's a Service Worker!

Service Workers

Quick Overview

Vite-plugin-pwa is a Vite plugin that adds PWA (Progressive Web App) support to your Vite projects. It integrates seamlessly with Vite's build process, generating a service worker and manifest file to transform your web application into a PWA with offline capabilities and improved performance.

Pros

  • Easy integration with Vite projects
  • Automatic generation of service worker and manifest file
  • Customizable PWA settings and features
  • Supports multiple PWA strategies (e.g., offline-first, network-first)

Cons

  • Limited to Vite-based projects
  • May require additional configuration for complex PWA scenarios
  • Documentation could be more comprehensive for advanced use cases

Code Examples

  1. Basic usage in vite.config.js:
import { defineConfig } from 'vite'
import { VitePWA } from 'vite-plugin-pwa'

export default defineConfig({
  plugins: [
    VitePWA({ registerType: 'autoUpdate' })
  ]
})
  1. Custom PWA configuration:
import { VitePWA } from 'vite-plugin-pwa'

export default {
  plugins: [
    VitePWA({
      manifest: {
        name: 'My PWA App',
        short_name: 'MyPWA',
        theme_color: '#ffffff',
        icons: [
          {
            src: '/icon-192x192.png',
            sizes: '192x192',
            type: 'image/png'
          }
        ]
      },
      workbox: {
        runtimeCaching: [
          {
            urlPattern: /^https:\/\/api\.example\.com\/.*/i,
            handler: 'NetworkFirst',
            options: {
              cacheName: 'api-cache'
            }
          }
        ]
      }
    })
  ]
}
  1. Registering the service worker in your main JavaScript file:
import { registerSW } from 'virtual:pwa-register'

const updateSW = registerSW({
  onNeedRefresh() {
    // Show a prompt to the user to refresh the app
  },
  onOfflineReady() {
    console.log('App is ready for offline use')
  }
})

Getting Started

  1. Install the plugin:

    npm install -D vite-plugin-pwa
    
  2. Add the plugin to your vite.config.js:

    import { defineConfig } from 'vite'
    import { VitePWA } from 'vite-plugin-pwa'
    
    export default defineConfig({
      plugins: [
        VitePWA({
          registerType: 'autoUpdate',
          manifest: {
            name: 'My PWA App',
            short_name: 'MyPWA',
            theme_color: '#ffffff',
            icons: [
              {
                src: '/icon-192x192.png',
                sizes: '192x192',
                type: 'image/png'
              }
            ]
          }
        })
      ]
    })
    
  3. Build your project with npm run build and serve the dist folder to see your PWA in action.

Competitor Comparisons

12,265

📦 Workbox: JavaScript libraries for Progressive Web Apps

Pros of Workbox

  • More comprehensive and flexible PWA toolset
  • Extensive documentation and community support
  • Suitable for various build systems and frameworks

Cons of Workbox

  • Steeper learning curve for beginners
  • Requires more manual configuration
  • May be overkill for simple PWA projects

Code Comparison

Workbox:

importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js');

workbox.routing.registerRoute(
  ({request}) => request.destination === 'image',
  new workbox.strategies.CacheFirst()
);

vite-plugin-pwa:

import { VitePWA } from 'vite-plugin-pwa';

export default defineConfig({
  plugins: [
    VitePWA({
      registerType: 'autoUpdate',
      workbox: {
        globPatterns: ['**/*.{js,css,html,ico,png,svg}']
      }
    })
  ]
});

The Workbox code demonstrates manual service worker configuration, while vite-plugin-pwa integrates PWA functionality directly into the Vite build process with minimal configuration. Workbox offers more granular control but requires more setup, whereas vite-plugin-pwa provides a simpler, more streamlined approach for Vite projects.

Offline plugin (ServiceWorker, AppCache) for webpack (https://webpack.js.org/)

Pros of offline-plugin

  • More mature and battle-tested, with a longer history of use in production environments
  • Supports a wider range of build tools and frameworks, including webpack, Rollup, and others
  • Offers more granular control over caching strategies and offline behavior

Cons of offline-plugin

  • Less integrated with Vite's ecosystem and may require additional configuration
  • Not specifically optimized for Vite's build process, potentially leading to slower builds
  • May have a steeper learning curve for developers already familiar with Vite's plugin system

Code Comparison

offline-plugin configuration:

new OfflinePlugin({
  caches: {
    main: ['index.html', 'app.js', 'app.css'],
    additional: ['*.chunk.js']
  },
  ServiceWorker: {
    events: true
  }
})

vite-plugin-pwa configuration:

import { VitePWA } from 'vite-plugin-pwa'

export default {
  plugins: [
    VitePWA({
      registerType: 'autoUpdate',
      workbox: {
        globPatterns: ['**/*.{js,css,html,ico,png,svg}']
      }
    })
  ]
}
4,872

✈️ Easily create sites that work offline as well as online

Pros of UpUp

  • Lightweight and easy to implement for basic offline functionality
  • Works with any web technology stack, not tied to a specific framework
  • Focuses on simplicity and quick setup for offline content caching

Cons of UpUp

  • Limited features compared to more comprehensive PWA solutions
  • Lacks integration with modern build tools and ecosystems
  • May require more manual configuration for advanced use cases

Code Comparison

UpUp:

upup.start({
  'content-url': 'offline.html',
  'assets': ['img/logo.png', 'css/style.css', 'js/app.js']
});

vite-plugin-pwa:

import { VitePWA } from 'vite-plugin-pwa'

export default defineConfig({
  plugins: [
    VitePWA({ registerType: 'autoUpdate' })
  ]
})

UpUp provides a simple API for basic offline functionality, while vite-plugin-pwa offers more comprehensive PWA features integrated with the Vite build process. UpUp is framework-agnostic and easier to set up for simple use cases, but vite-plugin-pwa provides more advanced PWA capabilities and seamless integration with Vite-based projects.

It's online. It's offline. It's a Service Worker!

Pros of serviceworker-cookbook

  • Comprehensive collection of service worker recipes and examples
  • Educational resource with detailed explanations for each recipe
  • Covers a wide range of service worker use cases and scenarios

Cons of serviceworker-cookbook

  • Not specifically designed for integration with Vite or other build tools
  • Requires manual implementation and adaptation for specific projects
  • May not include the latest service worker features or best practices

Code Comparison

serviceworker-cookbook example (basic service worker registration):

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js')
    .then(registration => console.log('SW registered'))
    .catch(error => console.log('SW registration failed'));
}

vite-plugin-pwa example (configuration in vite.config.js):

import { VitePWA } from 'vite-plugin-pwa'

export default {
  plugins: [
    VitePWA({ registerType: 'autoUpdate' })
  ]
}

The serviceworker-cookbook provides a more hands-on approach to understanding and implementing service workers, while vite-plugin-pwa offers a streamlined integration with Vite projects, automating much of the service worker setup and configuration process.

Service Workers

Pros of ServiceWorker

  • Provides a standardized, low-level API for implementing service workers
  • Offers more flexibility and control over caching strategies and offline functionality
  • Can be used with any web application framework or build tool

Cons of ServiceWorker

  • Requires more manual configuration and boilerplate code
  • Lacks built-in integration with specific build tools or frameworks
  • May require additional tooling for optimal development experience

Code Comparison

ServiceWorker:

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request).then((response) => {
      return response || fetch(event.request);
    })
  );
});

vite-plugin-pwa:

import { VitePWA } from 'vite-plugin-pwa';

export default {
  plugins: [
    VitePWA({ registerType: 'autoUpdate' })
  ]
};

The ServiceWorker example shows a basic fetch event handler for caching, while the vite-plugin-pwa example demonstrates how to integrate PWA functionality into a Vite project with minimal configuration.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

vite-plugin-pwa - Zero-config PWA for Vite
Zero-config PWA Framework-agnostic Plugin for Vite

NPM version NPM Downloads Docs & Guides
GitHub stars


🚀 Features

  • 📖 Documentation & guides
  • 👌 Zero-Config: sensible built-in default configs for common use cases
  • 🔩 Extensible: expose the full ability to customize the behavior of the plugin
  • 🦾 Type Strong: written in TypeScript
  • 🔌 Offline Support: generate service worker with offline support (via Workbox)
  • ⚡ Fully tree shakable: auto inject Web App Manifest
  • 💬 Prompt for new content: built-in support for Vanilla JavaScript, Vue 3, React, Svelte, SolidJS and Preact
  • ⚙️ Stale-while-revalidate: automatic reload when new content is available
  • ✨ Static assets handling: configure static assets for offline support
  • 🐞 Development Support: debug your custom service worker logic as you develop your application
  • 🛠️ Versatile: integration with meta frameworks: îles, SvelteKit, VitePress, Astro, Nuxt 3 and Remix
  • 💥 PWA Assets Generator: generate all the PWA assets from a single command and a single source image
  • 🚀 PWA Assets Integration: serving, generating and injecting PWA Assets on the fly in your application

📦 Install

From v0.17, vite-plugin-pwa requires Vite 5.

From v0.16 vite-plugin-pwa requires Node 16 or above: workbox v7 requires Node 16 or above.

From v0.13, vite-plugin-pwa requires Vite 3.1 or above.

npm i vite-plugin-pwa -D 

# yarn 
yarn add vite-plugin-pwa -D

# pnpm 
pnpm add vite-plugin-pwa -D

🦄 Usage

Add VitePWA plugin to vite.config.js / vite.config.ts and configure it:

// vite.config.js / vite.config.ts
import { VitePWA } from 'vite-plugin-pwa'

export default {
  plugins: [
    VitePWA()
  ]
}

Read the 📖 documentation for a complete guide on how to configure and use this plugin.

Check out the client type declarations client.d.ts for built-in frameworks support.

👀 Full config

Check out the type declaration src/types.ts and the following links for more details.

📄 License

MIT License © 2020-PRESENT Anthony Fu

NPM DownloadsLast 30 Days