Workbox, the easier way of adding a service worker to your web app.

Bakani Pilime
codeburst
Published in
4 min readOct 28, 2017

--

Workbox is a collection of libraries and build tools that make it easy to store your website’s files locally, on your users’ devices. (Workbox website)

Workbox combines a set of well trusted build tools and libraries to help you generate the right Service Worker for your web app. If you don’t already know what it is, a service worker is a Javascript file that runs in the background of your web app to add functionality like Caching, Background Sync, Push Notifications together with other useful APIs available on modern browsers.

Service Workers have become so popular because of the relatively new Progressive Web Applications, which are simply a way of progressively enhancing user experience by adding functionality to a web app for as long as the user’s browser supports the functionality (possible via feature detection). This is important because whilst browsers may be really improving as a result of advancements on mobile in terms of specs, it’s still important to cater for everyone and all devices because you never know who your paying customer is.

So where does Workbox come in?

Well, like the description above puts it, Workbox is a collection of tools which help you to generate a service worker suited for your use case. Because Workbox is also a collection of best practices, this means you no longer need to bloat your app with confusing boilerplate or copy-paste code from Stack Overflow. Instead you get well written & easy to understand code in fewer lines. Workbox’s simplicity actually empowers you to do more, with less.

Jeff Posnick, in his talk at #ChromeDevSummit17 used the following code snippets to illustrate how simple life is with Workbox. Watch “Workbox: Flexible PWA Libraries (Chrome Dev Summit 2017)” by Jeff Posnick here.

Normal code to retrieve from cache, but fetch an update from network for next time, aka Stale-while-revalidate Strategy.

All that is reduced to…

One line, cleaner, simpler.

Or if you want to have options on how & when the cache is updated, you can just …

Still not bad right?

Getting Started

Workbox comes with a CLi. To install it simply run

npm install -g workbox-cli

And to create a service worker, run

workbox generate:sw

This will create a basic service worker using Workbox’s default configuration. You can provide your own config by specifying it in your generate:sw command as follows:

workbox generate:sw --config-file=./path/to/config.js

A typical Workbox config can specify things like the directory to cache, destination of the generated service worker, cache name & expiration, and even the cache strategy to use for a given route. An example is given below.

A typical workbox config.

So using this configuration, the following service worker is generated.

Again, simple, cleaner, easy-to-follow code. A FileManifest is an array of cacheable objects.

Integration with build systems

This is perhaps the most awesome part of Workbox. There is so much ease when integrating Workbox into your preferred build system. On the Workbox website, there are examples on how to integrate with the most widely used i.e. Webpack, Gulp & npm-scripts. I use Webpack and npm-scripts (sometimes together) to build my Vue.Js projects. Workbox has a webpack plugin which you can simply install with

npm install workbox-webpack-plugin --save-dev

This plugin must be appended (or placed appropriately) in your plugins array in webpack.config.js (or webpack.prod.conf.js) using the following code.

 const path = require('path');
const workboxPlugin = require('workbox-webpack-plugin');

const DIST_DIR = 'dist';

module.exports = { /* Do the usual webpack stuff. */
plugins: [ /* Call the plugin. */
...
new workboxPlugin({
globDirectory: DIST_DIR,
globPatterns: ['**/*.{html,js,css}'],
swDest: path.join(DIST_DIR, 'sw.js'),
}),
]
};

If you have a Workbox config file you can use the plugin with that config like so...

plugins: [ /* Call the plugin. */
...
new workboxPlugin(require('./path/to/workbox/config.js')),
]

I even wrote my own Webpack plugin to add the service worker to the html and used cheerio to parse the html.

So just like that I have integrated Workbox to generate a service worker every time I run npm run build, and also made sure that the service worker is added to index.html of my web app. Now users can enjoy a faster web experience and continue using the web app even when offline.

Conclusion

Progressive Web Apps seem to have gained the attention they deserve. They bring the power of native to the web (offline use) and promote user engagement (via Web Push Notifications) and many more. All these awesome functionalities for your web app start off with a service worker, and Workbox makes this process of generating a service worker easier. Do check out the official documentation for Workbox to see more of what it can do like offline Google Analytics and Background Sync.

--

--

Lover of God, code & food. Backend Developer. Guardian of the localhost.