DEV Community

Rishi Raj Jain
Rishi Raj Jain

Posted on • Updated on • Originally published at rishi-raj-jain.Medium

Custom Service Worker in any app with esbuild

Lately I’ve been exploring use of Service Workers in web apps. Use cases include prefetching content at scale, speeding up your website, handling failovers and possibly many more. One of the problems that I continuously face is the need to adjust my service worker according to the framework, well no more. Let’s see what gold I dig up last week below 👇🏻

Where it started?

I was trying to set up a custom service worker with Angular 11, and the guide https://angular.io/guide/service-worker-getting-started asked me to install angular/pwa module, read https://angular.io/guide/service-worker-communications and then adapt to the angular’s way of creating service worker. Well, seemed like a lot of work to me, so I set out to create a framework-agnostic process for adding a custom service worker. Reflecting back, I think it was fairly easier with Vue 2 and 3, yet felt like a hacky way.

Show me the solution!

Step 0. Install esbuild

Step 1. Create workbox-config.js:
Learn more about what’s there in workbox config here:

module.exports = {
  globDirectory: "dist/",
  globPatterns: [
    "**/*.{css,eot,html,ico,jpg,js,json,png,svg,ttf,txt,webmanifest,woff,woff2,webm,xml}",
  ],
  globFollow: true,
  globStrict: true,
  globIgnores: [
    "**/*-es5.*.js",
    "3rdpartylicenses.txt",
    "assets/images/icons/icon-*.png",
  ],
  dontCacheBustURLsMatching: new RegExp(".+.[a-f0-9]{20}..+"),
  maximumFileSizeToCacheInBytes: 5000000,
  swSrc: "dist/service-worker.js",
  swDest: "dist/service-worker.js",
};
Enter fullscreen mode Exit fullscreen mode

Step 2. Create compile_sw.js:

const { build } = require("esbuild")

build({
  entryPoints: ["./path/to/service-worker.js"],
  outfile: "./dist/service-worker.js",
  minify: true,
  bundle: true,
  define: {
    'process.env.NODE_ENV': '"production"',
    'process.env.SOME_VARIABLE': '"SOME_VALUE"'
  },
}).catch(() => process.exit(1))
Enter fullscreen mode Exit fullscreen mode

Step 3. Compile and inject:

npx workbox-cli injectManifest && node compile_sw.js
Enter fullscreen mode Exit fullscreen mode

Step 4. Register the Service Worker ✨

<script>
// Check that service workers are supported
if ('serviceWorker' in navigator) {
  // Use the window load event to keep the page load performant
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/service-worker.js');
  });
}
</script>
Enter fullscreen mode Exit fullscreen mode

That’s all, enjoy! I hope this helps!

Top comments (0)