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:
Step 2. Create compile_sw.js:
Step 3. Compile and inject:
Step 4. Register the Service Worker ✨
That’s all, enjoy! I hope this helps!