Simplifying Progressive Web App (PWA) Development with Vite: A Beginner's Guide
Tags: vite, pwa, react, lighthouse
Published: 2023-07-02 11:31:22

If you're new to PWA development, navigating through the vast array of tools and frameworks can be overwhelming. However, Vite, which is a lightning-fast build tool, has revolutionized the PWA development workflow by simplifying it.

## Key Components of PWA:

First we must understand what actually is a PWA. Progressive Web Apps are web applications that utilize modern web capabilities to deliver an app-like experience to users. They are designed to be fast, reliable, and engaging, regardless of the user's device or network conditions. PWAs leverage key technologies such as the web app manifest, service workers, and caching mechanisms to enable features like offline functionality, push notifications, and seamless installation. In other words, PWAs are a hybrid version of Web and App, but under the hood they are actually JS driven Websites.

Let's dive deep into the key 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, providing a more immersive experience.

A bare minimum **manifest.json** file:

```json
{
  "name": "Simplifying Progressive Web App (PWA) Development with 
           Vite: A 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
  ]
}

```

### 2- Service Workers:
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. Service workers also enable push notifications and background sync, enhancing the user experience.

Registering a service worker in main JavaScript file:

```javascript
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);
      });
  });
}
```

### 3- Caching:
Caching is a vital aspect of PWAs as it allows the app to load quickly and work offline. By utilizing caching strategies, developers can store and serve static assets, API responses, and other 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 are adding an event listener for fetch requests which checks if the request matches the cache request then return cached response, otherwise call the fetch request.

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

## 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:

```bash
npm install vite-plugin-pwa --save-dev
```

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

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

export default {
  plugins: [
    VitePWA()
  ]
};
```

3- Customize the plugin option to fit your requirements:

```javascript
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}"],
      }
    })
  ]
};
```

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

```bash
>> npm run build
>> npm run preview
```
**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/orlqtxdox38ok6jqop2n.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/siqcqcupjc8r6w37nkt1.PNG)


---

If you want to learn more about the vite-plugin-pwa library, you can visit their [official docs.](https://vite-pwa-org.netlify.app/)

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!_**