Progressive Web App (PWA) with Vite : Development Guide

hamdankhan364

Hamdan Khan

Posted on July 2, 2023

Progressive Web App (PWA) with Vite : Development Guide

If you are new to PWA development and looking for a way to convert your Single Page App into a PWA, this article can be helpful for you as it provides both a technical and a conceptual POV of PWAs generally and in the context of Vite. (Just to let you know, Vite provides one of the most simplified PWA development experience)

Let's start by understanding the basics of a PWA:

Key Components of PWA:

Progressive Web Apps are web applications that deliver an app-like experience to users. Think of it as a website that you can download and use even when you are offline. They are designed to WORK regardless of the user's device or network conditions.
You might be wondering how is that possible for me when my website makes use of the countless API calls. How will the website work without the internet? That's the tricky part. Let's discover the components of the PWA and understand how they make sure that the website , I mean application runs in the aforementioned conditions.

To be fair, PWAs are a hybrid version of Web and App, but under the hood they are actually JS driven Websites.

Let's take a look at the components of a PWA:

1- Web App Manifest:

The web app manifest is a JSON file that provides essential metadata about the PWA, including its name, icons, colors, and other properties. It allows the PWA to be installed on the user's home screen, similar to a native app.

A barebone manifest.json file:

{
  "name": "Progressive Web App (PWA) Development with 
           Vite: Beginner's Guide",
  "short_name": "PWA Guide",
  "start_url": "/",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#000000",
  "icons": [
    {
      "src": "/images/icon-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "/images/icon-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
    // can also include icons of other dimesnions
  ]
}

Enter fullscreen mode Exit fullscreen mode

2- Service Workers:

This component will answer the questions about the connectivity of a PWA. Service workers are JavaScript files that act as a proxy between the web app and the network. They enable offline functionality by intercepting network requests, caching resources, and serving them even when the user is offline.
Think of it as a placeholder server which substitutes your main server. The Service workers are responsible for dealing with the API requests.

// First visit - service worker is installed
Client -> Server

// Online mode - service worker acting as a proxy
Client -> Service Worker -> Server

// Offline mode - service worker responding with cached responses
Client -> Service Worker -> Cache

Enter fullscreen mode Exit fullscreen mode

Service workers also enable features like push notifications and background sync.

Registering a service worker in main JavaScript file:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/service-worker.js')
      .then(registration => {
        console.log('Service Worker registered:', registration);
      })
      .catch(error => {
        console.log('Service Worker registration failed:', error);
      });
  });
}
Enter fullscreen mode Exit fullscreen mode

3- Caching:

Caching is basically how the PWAs are able to deal with incoming API requests in offline mode. It also allows the app to load quickly. By utilizing caching strategies, developers can store and serve static assets, API responses, and other static data. Different caching mechanisms, such as runtime caching and pre-caching, ensure that the PWA remains accessible even when the network connection is poor or non-existent.

In this code, we have added an event listener for API requests which checks if the current request matches the cached request it returns the cached response, otherwise call the API request.

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(response => {
        if (response) {
          return response;
        }
        return fetch(event.request);
      })
  );
});
Enter fullscreen mode Exit fullscreen mode

PWA creation with Vite:

Creating PWA without any framework and tool can sometimes be overwhelming for beginners. Vite abstracts away the complexity of manual PWA creation and integrates seamlessly into your development process with the help of a plugin.

Vite PWA Plugin:

The Vite PWA plugin provides an efficient and streamlined way to add PWA functionality to your Vite projects.

To add Vite PWA plugin to your app, follow these steps:

1- Install the vite-plugin-pwa:

npm install vite-plugin-pwa --save-dev
Enter fullscreen mode Exit fullscreen mode

2- Import the plugin into your 'vite.config.js' file:

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

export default {
  plugins: [
    VitePWA()
  ]
};
Enter fullscreen mode Exit fullscreen mode

3- Customize the plugin option to fit your requirements:

export default {
  plugins: [
    VitePWA({
      // generates 'manifest.webmanifest' file on build
      manifest: {
        // caches the assets/icons mentioned (assets/* includes all the assets present in your src/ directory) 
        includeAssets: ["favicon.ico", "apple-touch-icon.png", "assets/*"]
        name: 'Simplifying Progressive Web App (PWA) Development with Vite: A Beginners Guide',
        short_name: 'PWA Guide',
        start_url: '/',
        background_color: '#ffffff',
        theme_color: '#000000',
        icons: [
          {
            src: '/images/icon-192x192.png',
            sizes: '192x192',
            type: 'image/png'
          },
          {
            src: '/images/icon-512x512.png',
            sizes: '512x512',
            type: 'image/png'
          }
        ]
      },
      workbox: {
        // defining cached files formats
        globPatterns: ["**/*.{js,css,html,ico,png,svg,webmanifest}"],
      }
    })
  ]
};
Enter fullscreen mode Exit fullscreen mode

4- Build the app to generate PWA files and run the server:

>> npm run build
>> npm run preview
Enter fullscreen mode Exit fullscreen mode

Note: Only works after building the app.

5- To check if everything is working properly and PWA functionality is achieved, you can look for the Install App icon in the URL bar.

Example of installabe Web Icon

You can also check the Application section in Chrome Devtools which provides useful information about the manifest, registered service worker, and cache storage of the PWA.

The Lighthouse section of Chrome DevTools also provide an insight on the Website's performance score and PWA functionality.

After Running Page Analysis


If you want to learn more about the vite-plugin-pwa library, you can visit their official docs.

If you have any queries or need further assistance, please leave your questions in the comment section below. I'll be more than happy to help you on your PWA development journey!

Happy Coding!

💖 💪 🙅 🚩
hamdankhan364
Hamdan Khan

Posted on July 2, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related