If you just want to see a working example, clone this repo.
They do have access to other APIs, such as IndexedDB, and can act as a proxy between your application and the network.
Workbox uses these features to cache network requests using various strategies, so that our app can be used offline as well as possible, transparently for the user.
We want our app to be completely available offline, but we can’t expect the user to request every file himself as he’s using the application just so that we can cache them.
We will give Workbox a list of files we know need to be cached in advance, thus, precaching.
Precaching Rollup bundles
In the first part of this guide, we configured Rollup to output 2 formats : esm and system. Since we only want to cache relevant files, we need to generate a ServiceWorker for each format.
We’ll be using workbox-cli (there is a rollup plugin for workbox, but I couldn’t get it to work correctly with multiple outputs).
As we’re adding a new step to our build process, let’s install
npm-run-all as well to help us chain scripts together.
npm install --save-dev workbox-cli npm-run-all
We need a template src/sw.js file:
registerRoute() call with unpkg.com is obviously not necessary if you’re not using this CDN. It is included here because we use it in our examples).
We will create a configuration file for each output (esm and system):
modifyURLPrefix option : I’ve added it to fix problems with Netlify, but depending on your hosting solution, you probably won’t need it.
Add the following scripts to package.json:
HTTP server configuration
Browsers save ServiceWorker files in a different way than traditional HTTP requests, which means we need to disable HTTP cache:
Additionally, we decided to put our sw.js files in subdirectories of the server root (public/js/esm/ and public/js/system/), so we need a header to avoid unenjoyable warnings:
Here’s a configuration for the server that we set up in the previous article,
Registering our Service Workers
Finally, we need to actually register sw.js from the browser, depending on which output format is used. Here’s an example of how to do it in index.html from the example repository:
In part 3, we will cover testing tools (unit and end-to-end), continuous integration and deployment.
If you have suggestions, corrections or enhancements, please tell me in the comments and I’ll update this post.