ServiceWorker generation plugin for Hapi.js
hapi-sw is a Hapi.js plugin that creates a Service Worker with sw-precache.
Service Workers are a building block for progressive web apps, but require intricate configuration. There are already great projects like [sw-toolbox][sw-toolbox] and the aforementioned sw-precache that can help you generate Service Worker code effectively, but typically require some cross-cutting information that might not be readily available at build-time. Additionally, these tools make assumptions that favor static assets while ignoring the server-side routes which ultimately deliver those assets.
This plugin addresses that problem by using generating a properly configured Service Worker dynamically, based on the assets and routes available to your server.
Add hapi-sw as a dependency to your Hapi.js project:
npm install hapi-sw --save
Register the plugin with a connected Hapi server, passing your configuration for sw-precache as options for the plugin/
const Hapi = require('hapi')
const server = new Hapi.Server()
server.connection({ port: 3000 })
server.register({
register: require('hapi-sw'),
options: {
staticFileGlobs: [
`assets/**.{css,js}`,
`assets/img/**.*`
],
runtimeCaching: [
{
urlPattern: new RegExp(CDN_DOMAIN),
handler: 'cacheFirst'
}
]
}
}, (err) => {
// service worker now available at /service-worker.js
})
See the example code to get a more detailed understanding of what a typical setup might look like. Here's how to run it locally:
$ npm install
$ cd example
$ node index.js
-
Routes for the Service Worker and it's registration code are added
/service-worker.js
is source of the worker generated by sw-precache- This file is generated dynamically whenever the server starts
- TODO: in the future there should be an option to write to a file
/service-worker-registration.js
is the example registration file, recommended by the sw-precache
-
A listener is added to the 'route' event
- Whenever any subsequent routes are added to the server, hapi-sw will inspect them for any custom plugin settings
- This allows for route-scoped rules to be added to the options sent to sw-precache
- For instance, you could add a rule on a route to add that url to the pre-fetched cached:
server.route({
path: '/',
config: {
plugins: {
sw: {
dynamicUrlToDependencies: [
'./templates/homepage.html',
'./templates/layout.html'
]
}
}
}
})
All top-level settings given at registration are passed through sw-precache. See the sw-precache Options Parameter documentation for the full list of options and what they do.
The following options may be set in a route's sw
plugin config:
dynamicUrlToDependencies
dontCacheBustUrlsMatching
navigateFallback
runtimeCaching
Any rules passed to these settings will be scoped to the route's path unless otherwise specified.