DEV Community

Rishi Raj Jain
Rishi Raj Jain

Posted on

How to bundle your custom service worker in Vite? (without using PWA)

In this tutorial, we'll walk through the process of bundling and minifying a custom service worker to your Vite project without using a PWA (Progressive Web App) Plugin/NPM Package. By the end, you'll have a service worker bundled with your Vite app, enabling you to cache assets and enhance performance.

1. Creating a Service Worker

Let's start by creating a simple service worker script that will be included at the root of your project repository.

// File: service-worker.js

console.log("Hey, I am a service worker.");
Enter fullscreen mode Exit fullscreen mode

Now, let's move on to the steps required to bundle this service worker with your Vite application.

2. Installing register-service-worker Package

Next, we need to install the register-service-worker package, which helps in registering (and updating) the service worker within your Vite app.

npm install register-service-worker
Enter fullscreen mode Exit fullscreen mode

3. Updating the Entrypoint

To make the service worker available for your Vite app, you need to import and register it in your main JavaScript file (typically main.js).

// File: src/main.js

// ...

createApp(App).mount('#app')

import { register } from "register-service-worker";

register(`/service-worker.js`)
Enter fullscreen mode Exit fullscreen mode

With this step, your service worker is ready to be registered when your app loads.

4. Creating a Post-Build Vite Plugin

Vite allows us to create custom build plugins. In this case, we'll create a post build plugin to bundle the service worker script using esbuild's buildSync API. This will ensure that the service worker script is minified and bundled in the final build of your Vite app.

// File: vite.config.js

// ...
import { join } from "node:path";
import { buildSync } from "esbuild";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    // ...
    {
      apply: "build",
      enforce: "post",
      transformIndexHtml() {
        buildSync({
          minify: true,
          bundle: true,
          entryPoints: [join(process.cwd(), "service-worker.js")],
          outfile: join(process.cwd(), "dist", "service-worker.js"),
        });
      },
    },
  ],
});

Enter fullscreen mode Exit fullscreen mode

This plugin will bundle your service worker and place it in the dist directory after the Vite build process.

You're Done!

In this guide, we've learned how to minify and bundle a custom service worker with your Vite application without using PWA Plugin / NPM Package. This setup enables you to cache assets and improve your app's performance while maintaining full control over the service worker's behavior.

Top comments (0)