workbox-build

This Node module can be used to generate a list of assets that should be precached in a service worker, generating a hash that can be used to intelligently update a cache when the service worker is updated.

This module will use glob patterns to find assets in a given directory and use the resulting URL and hash data for one of the follow uses:

  1. Generate a complete service worker with precaching and some basic configurable options. See generateSW().
  2. Inject a manifest into an existing service worker. This allows you to control your own service worker while still taking advantage of workboxSW.precache() logic. See injectManifest().
  3. Generate a manifest file. This is useful if you want to read in the urls and revision details via an import script or ES2015 module import. See generateFileManifest().
  4. Get a JS object of the manifest details. Can be used in a build process if you want to inject the manifest into a file or template yourself. See getFileManifestEntries().
Examples

Generate a complete service worker that will precache the discovered assets.

const swBuild = require('workbox-build');

swBuild.generateSW({
  globDirectory: './build/',
  globPatterns: ['**\/*.{html,js,css}'],
  globIgnores: ['service-worker.js','admin.html'],
  swDest: './build/sw.js',
  templatedUrls: {
    '/shell': ['shell.hbs', 'main.css', 'shell.css'],
  },
})
.then(() => {
  console.log('Service worker generated.');
});

Generate a file containing the assets to precache.

const swBuild = require('workbox-build');

swBuild.generateFileManifest({
  globDirectory: './build/',
  globPatterns: ['**\/*.{html,js,css}'],
  globIgnores: ['service-worker.js','admin.html'],
  mainfestDest: './build/scripts/manifest.js',
  templatedUrls: {
    '/shell': ['shell.hbs', 'main.css', 'shell.css'],
  },
})
.then(() => {
  console.log('Build file has been created.');
});

Get an Array of files with revision details.

const swBuild = require('workbox-build');

swBuild.getFileManifestEntries({
  globDirectory: './build/',
  globPatterns: ['**\/*.{html,js,css}'],
  globIgnores: ['service-worker.js','admin.html'],
  templatedUrls: {
    '/shell': ['shell.hbs', 'main.css', 'shell.css'],
  },
})
.then((fileDetails) => {
  // An array of file details include a `url` and `revision` parameter.
});

Instance Methods

(static) this.generateFileManifest(input) Promise

This method will generate a file manifest that can be used in a service worker to precache assets.

Example

Generate a build manifest of static assets, which can used with a service worker.

const swBuild = require('workbox-build');

swBuild.generateFileManifest({
  manifestDest: './build/manifest.js'
  globDirectory: './build/',
  globPatterns: ['**\/*.{html,js,css}'],
  globIgnores: ['admin.html'],
  format: 'iife', // alternatively, use 'es'
})
.then(() => {
  console.log('Build Manifest generated.');
});
Parameters
input Object
Properties
format String (Optional)

There are some options for how the file manifest is formatted in the final output. The format can be one of the following values:

Default value is 'iife'.

manifestDest String

The file path and name where the file manifest should be written (i.e. ./build/precache-manifest.js).

globDirectory String

The directory you wish to run the globPatterns against.

globPatterns Array.<String>

Files matching against any of these glob patterns will be included in the file manifest.

globIgnores String | Array.<String> (Optional)

Files matching against any of these glob patterns will be excluded from the file manifest, even if the file matches against a globPatterns pattern.

templatedUrls Object.<String, (Array|String)> (Optional)

If a URL is rendered with templates on the server, its contents may depend on multiple files. This maps URLs to an array of file names, or to a string value, that uniquely determines the URL's contents.

modifyUrlPrefix String (Optional)

An object of key value pairs where URL's starting with the key value will be replaced with the corresponding value.

maximumFileSizeToCacheInBytes number (Optional)

This value can be used to determine the maximum size of files that will be precached.

Defaults to 2MB.

dontCacheBustUrlsMatching RegExp (Optional)

Assets that match this regex will not have their revision details included in the precache. This is useful for assets that have revisioning details in the filename.

Returns Promise

The returned promise resolves once the manifest file has been generated.

(static) this.generateSW(input) Promise

This method will generate a working service worker with an inlined file manifest.

Example

Generate a service worker with precaching support.

const swBuild = require('workbox-build');

swBuild.generateSW({
  swDest: './build/sw.js',
  globDirectory: './build/',
  globPatterns: ['**\/*.{html,js,css}'],
  globIgnores: ['admin.html'],
  templatedUrls: {
    '/shell': ['shell.hbs', 'main.css', 'shell.css'],
  },
})
.then(() => {
  console.log('Service worker generated.');
});
Parameters
input Object
Properties
swDest String

The file path and name you wish to writh the service worker file to.

globDirectory String

The directory you wish to run the globPatterns against.

globPatterns Array.<String>

Files matching against any of these glob patterns will be included in the file manifest.

globIgnores String | Array.<String> (Optional)

Files matching against any of these glob patterns will be excluded from the file manifest, even if the file matches against a globPatterns pattern.

templatedUrls Object.<String, (Array|String)> (Optional)

If a URL is rendered with templates on the server, its contents may depend on multiple files. This maps URLs to an array of file names, or to a string value, that uniquely determines the URL's contents.

navigateFallback string (Optional)

This URL will be used as a fallback if a navigation request can't be fulfilled. Normally this URL would be precached so it's always available. This is particularly useful for single page apps where requests should go to a single URL.

navigateFallbackWhitelist Array.<Regexp> (Optional)

An optional Array of regexs to restrict which URL's use the navigateFallback URL.

cacheId String (Optional)

An optional ID to be prepended to caches used by workbox-build. This is primarily useful for local development where multiple sites may be served from the same http://localhost origin.

skipWaiting Boolean (Optional)

When set to true the generated service worker activate immediately.

Defaults to false.

clientsClaim Boolean (Optional)

When set to true the generated service worker will claim any currently open pages.

Defaults to false.

directoryIndex string (Optional)

If a request for a URL ending in '/' fails, this value will be appended to the URL and a second request will be made.

Defaults to 'index.html'.

runtimeCaching Array.<Object> (Optional)

Passing in an array of objects containing a urlPattern and a handler parameter will add the appropriate code to the service work to handle run time caching for URL's matching the pattern with the associated handler behavior.

modifyUrlPrefix String (Optional)

An object of key value pairs where URL's starting with the key value will be replaced with the corresponding value.

ignoreUrlParametersMatching Array.<RegExp> (Optional)

Any search parameters matching against one of the regex's in this array will be removed before looking for a cache match.

handleFetch Boolean (Optional)

When set to false all requests will go to the network. This is useful during development if you don't want the service worker from preventing updates.

Defaults to true.

maximumFileSizeToCacheInBytes number (Optional)

This value can be used to determine the maximum size of files that will be precached.

Defaults to 2MB.

dontCacheBustUrlsMatching RegExp (Optional)

Assets that match this regex will not have their revision details included in the precache. This is useful for assets that have revisioning details in the filename.

Returns Promise

Resolves once the service worker has been generated with a precache list.

(static) this.getFileManifestEntries(input) Array.<ManifestEntry>

To get a list of files and revision details that can be used to ultimately precache assets in a service worker.

Parameters
input Object
Properties
globDirectory String

The directory you wish to run the globPatterns against.

globPatterns Array.<String>

Files matching against any of these glob patterns will be included in the file manifest.

globIgnores String | Array.<String> (Optional)

Files matching against any of these glob patterns will be excluded from the file manifest, even if the file matches against a globPatterns pattern.

templatedUrls Object.<String, (Array|String)> (Optional)

If a URL is rendered with templates on the server, its contents may depend on multiple files. This maps URLs to an array of file names, or to a string value, that uniquely determines the URL's contents.

modifyUrlPrefix String (Optional)

An object of key value pairs where URL's starting with the key value will be replaced with the corresponding value.

maximumFileSizeToCacheInBytes number (Optional)

This value can be used to determine the maximum size of files that will be precached.

Defaults to 2MB.

dontCacheBustUrlsMatching RegExp (Optional)

An optional regex that will return a URL string and exclude the revision details for urls matching this regex. Useful if you have assets with file revisions in the URL.

Returns Array.<ManifestEntry>

An array of ManifestEntries which will include a url and revision parameter.

(static) this.injectManifest(input) Promise

This method will read an existing service worker file and replace an empty precache() call, like: .precache([]), and replace the array with an array of assets to precache. This allows the service worker to efficiently cache assets for offline use.

Example

Generate a build manifest of static assets, which could then be used with a service worker.

const swBuild = require('workbox-build');

swBuild.injectManifest({
  globDirectory: './build/',
  globPatterns: ['**\/*.{html,js,css}'],
  globIgnores: ['admin.html'],
  swSrc: './src/sw.js',
  swDest: './build/sw.js',
})
.then(() => {
  console.log('Build Manifest generated.');
});
Parameters
input Object
Properties
swSrc String

File path and name of the service worker file to read and inject the manifest into before writing to swDest.

swDest String

The file path and name you wish to writh the service worker file to.

globDirectory String

The directory you wish to run the globPatterns against.

globPatterns Array.<String>

Files matching against any of these glob patterns will be included in the file manifest.

globIgnores String | Array.<String> (Optional)

Files matching against any of these glob patterns will be excluded from the file manifest, even if the file matches against a globPatterns pattern.

templatedUrls Object.<String, (Array|String)> (Optional)

If a URL is rendered with templates on the server, its contents may depend on multiple files. This maps URLs to an array of file names, or to a string value, that uniquely determines the URL's contents.

modifyUrlPrefix String (Optional)

An object of key value pairs where URL's starting with the key value will be replaced with the corresponding value.

maximumFileSizeToCacheInBytes number (Optional)

This value can be used to determine the maximum size of files that will be precached.

Defaults to 2MB.

dontCacheBustUrlsMatching RegExp (Optional)

An optional regex that will return a URL string and exclude the revision details for urls matching this regex. Useful if you have assets with file revisions in the URL.

Returns Promise

Resolves once the service worker has been written with the injected precache list.

Type Definitions

ManifestEntry

Properties

url String

The URL to the asset in the manifest.

revision String

The revision details for the file. This is a hash generated by node based on the file contents.