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 revision 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().

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 workboxBuild = require('workbox-build');

workboxBuild.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 Configuration
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).

Returns Promise

Resolves once the manifest file has been created.

(static) this.generateSW(input) Promise

This method will generate a working service worker with code to precache any assets found during the build process.

Example

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

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

workboxBuild.generateSW({
  globDirectory: './dist/',
  globPatterns: ['**\/*.{html,js,css}'],
  globIgnores: ['admin.html'],
  swDest: './dist/sw.js',
  templatedUrls: {
    '/shell': ['dev/templates/app-shell.hbs', 'dev/**\/*.css'],
  },
})
.then(() => {
  console.log('Service worker generated.');
});
Parameters
input Configuration
Returns Promise

Resolves once the service worker has been generated.

(static) this.getFileManifestEntries(input) Promise.<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 Configuration
Returns Promise.<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, find an instance of .precache([]), and replace the empty array with the contents of a precache manifest. This allows the service worker to efficiently cache assets for offline use, while still giving you control over the rest of the service worker's code.

Example

Takes an existing service worker file that includes a precache([]) placeholder, and injects a manifest of discovered assets into it.

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

workboxBuild.injectManifest({
  swSrc: './dev/sw.js',
  swDest: './dist/sw.js',
  globDirectory: './dist/',
  globPatterns: ['**\/*.{html,js,css}'],
  globIgnores: ['admin.html'],
  templatedUrls: {
    '/shell': ['dev/templates/app-shell.hbs', 'dev/**\/*.css'],
  },
})
.then(() => {
  console.log('Service worker generated.');
});
Parameters
input Configuration
Returns Promise

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

Type Definitions

Configuration

These are the full set of options that could potentially be used to configure one of the build tools. Each of the build tools has a slightly different way of providing this configuration:

  • When using the workbox-build module directly, pass the configuration object to appropriate method. For example, workboxBuild.injectManifest(configuration) or workboxBuild.generateSW(configuration).

  • When using the workbox-cli command line interface, use the --config-file flag to point to a CommonJS module file that assigns the configuration object to module.exports.

  • When using workbox-webpack-plugin within a Webpack build, pass the configuration object to the plugin's constructor, like new WorkboxBuildWebpackPlugin(configuration).

Some specific options might not make sense with certain combinations of interfaces. In those cases, the limitations are called out in the documentation, and may lead to build-time warnings or errors.

Each option documented here includes an example, which, for the sake of illustration, assumes the following local filesystem setup. Please adjust the example values to match your actual setup.

./
├── dev/
│   ├── app.js
│   ├── ignored.html
│   ├── image.png
│   ├── index.html
│   ├── main.css
│   ├── sw.js
│   └── templates/
│       └── app_shell.hbs
└── dist/
    ├── app.js
    ├── image.png
    ├── index.html
    ├── main.css
    └── sw.js

Properties

swDest String

The path to the final service worker file that will be created by the build process, relative to the current working directory.

E.g.: './dist/sw.js'

swSrc String

The path to the source service worker containing a precache([]) placeholder, which will be replaced with the precache manifest generated by the build.

E.g.: './dev/sw.js'

Note: This option is only valid when used with injectManifest().

globPatterns Array.<String>
<optional>
['**\/*.{js,css,html}']

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

E.g.: '**\/*.{js,css,html,png}'

globDirectory String

The base directory you wish to match globPatterns against, related to the current working directory.

E.g.: './dev'

globIgnores String | Array.<String>
<optional>
'node_modules'

Files matching against any of these glob patterns will be excluded from the file manifest, overriding any matches from globPatterns.

E.g. ['**\/ignored.html']

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

If a URL is rendered generated based on some server-side logic, its contents may depend on multiple files or on some other unique string value.

If used with an array of strings, they will be interpreted as glob patterns, and the contents of any files matching the patterns will be used to uniquely version the URL.

If used with a single string, it will be interpreted as unique versioning information that you've generated out of band for a given URL.

E.g.

{
  '/app-shell': [
    'dev/templates/app-shell.hbs',
    'dev/**\/*.css',
   ],
  '/other-page': 'my-version-info',
}
maximumFileSizeToCacheInBytes number
<optional>
2097152

This value can be used to determine the maximum size of files that will be precached. This prevents you from inadvertantly precaching very large files that might have been accidentally match your globPatterns values.

manifestTransforms Array.<ManifestTransform>
<optional>

An array of manifest transformations, which will be applied sequentially against the generated manifest. If modifyUrlPrefix or dontCacheBustUrlsMatching are also specified, their corresponding transformations will be applied first.

See ManifestTransform.

modifyUrlPrefix Object.<String, String>
<optional>

A mapping of prefixes that, if present in an entry in the precache manifest, will be replaced with the corresponding value.

This can be used to, for example, remove or add a path prefix from a manifest entry if your web hosting setup doesn't match your local filesystem setup.

As an alternative with more flexibility, you can use the manifestTransforms option and provide a function that modifies the entries in the manifest using whatever logic you provide.

E.g.

{
  '/prefix-to-remove': '',
}
dontCacheBustUrlsMatching RegExp
<optional>

Assets that match this regex will be assumed to be uniquely versioned via their URL, an exempted from the normal HTTP cache-busting that's done when populating the precache.

While not required, it's recommended that if your existing build process already inserts a [hash] value into each filename, you provide a RegExp that will detect those values, as it will reduce the amount of bandwidth consumed when precaching.

E.g. /\.\w{8}\./

navigateFallback String
<optional>

This will be used to create a NavigationRoute that will respond to navigation requests for URLs that that aren't precached.

This is meant to be used in a Single Page App scenario, in which you want all navigations to result in common App Shell HTML being reused.

It's not intended for use as a fallback that's displayed when the browser is offline.

Note: This option is only valid when used with generateSW(). When using injectManifest(), you can explicitly add in a call to registerNavigationRoute() in your swSrc file.

E.g. '/app-shell'

navigateFallbackWhitelist Array.<RegExp>
<optional>
/./

An optional array of regular expressions that restrict which URLs the navigation route applies to.

Note: This option is only valid when used with generateSW(). When using injectManifest(), you can explicitly add in the whitelist when calling registerNavigationRoute() in your swSrc file.

E.g. [/pages/, /articles/]

cacheId String
<optional>

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

Note: This option is only valid when used with generateSW(). When using injectManifest(), you can explicitly pass the desired value in to the WorkboxSW() constructor in your swSrc file.

E.g. 'my-app-name'

skipWaiting Boolean
<optional>
false

Whether or not the service worker should skip over the waiting lifecycle stage.

Note: This option is only valid when used with generateSW(). When using injectManifest(), you can explicitly pass the desired value in to the WorkboxSW() constructor in your swSrc file.

clientsClaim Boolean
<optional>
false

Whether or not the service worker should start controlling any existing clients as soon as it activates.

Note: This option is only valid when used with generateSW(). When using injectManifest(), you can explicitly pass the desired value in to the WorkboxSW() constructor in your swSrc file.

directoryIndex string
<optional>
'index.html'

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

This should be configured to whatever your web server is using, if anything, for its directory index.

Note: This option is only valid when used with generateSW(). When using injectManifest(), you can explicitly pass the desired value in to the WorkboxSW() constructor in your swSrc file.

runtimeCaching Array.<Object>
<optional>

Passing in an array of objects containing urlPatterns, handlers, and potentially options that will add the appropriate code to the generated service worker to handle runtime caching.

Requests for precached URLs that are picked up via globPatterns are handled by default, and don't need to be accomodated in runtimeCaching.

The handler values correspond the names of the strategies supported by workbox-sw.

Note: This option is only valid when used with generateSW(). When using injectManifest(), you can explicitly add in the corresponding runtime caching behavior via registerRoute() in your swSrc file.

E.g.

[{
  // You can use a RegExp as the pattern:
  urlPattern: /.jpg$/,
  handler: 'cacheFirst',
  // Any options provided will be used when
  // creating the caching strategy.
  options: {
    cacheName: 'image-cache',
    cacheExpiration: {
      maxEntries: 10,
    },
  },
}, {
  // You can also use Express-style strings:
  urlPattern: 'https://example.com/path/to/:file',
  handler: 'staleWhileRevalidate',
  options: {
    cacheableResponse: {
         statuses: [0],
    },
  },
}]
ignoreUrlParametersMatching Array.<RegExp>
<optional>
[/^utm_/]

Any search parameter names that match against one of the regex's in this array will be removed before looking for a precache match.

This is useful if your users might request URLs that contain, for example, URL parameters used to track the source of the traffic. Those URL parameters would normally cause the cache lookup to fail, since the URL strings used as cache keys would not be expected to include them.

You can use [/./] to ignore all URL parameters.

Note: This option is only valid when used with generateSW(). When using injectManifest(), you can explicitly pass the desired value in to the WorkboxSW() constructor in your swSrc file.

E.g. [/homescreen/]

handleFetch Boolean
<optional>
true

Whether or not workbox-sw should create a fetch event handler that responds to network requests. This is useful during development if you don't want the service worker serving stale content.

Note: This option is only valid when used with generateSW(). When using injectManifest(), you can explicitly pass the desired value in to the WorkboxSW() constructor in your swSrc file.

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.

this.ManifestTransform(manifestEntries) Array.<ManifestEntry>

A ManifestTransform function can be used to modify the modify the url or revision properties of some or all of the ManifestEntries in the manifest.

Deleting the revision property of an entry will cause the corresponding url to be precached without cache-busting parameters applied, which is to say, it implies that the URL itself contains proper versioning info. If the revision property is present, it must be set to a string.

Examples

A transformation that prepended the origin of a CDN for any URL starting with '/assets/' could be implemented as:

const cdnTransform = (manifestEntries) => manifestEntries.map(entry => {
  const cdnOrigin = 'https://example.com';
  if (entry.url.startsWith('/assets/')) {
    entry.url = cdnOrigin + entry.url;
  }
  return entry;
});

A transformation that removes the revision field when the URL contains an 8-character hash surrounded by '.', indicating that it already contains revision information:

const removeRevisionTransform = (manifestEntries) => {
  return manifestEntries.map(entry => {
    const hashRegExp = /\.\w{8}\./;
    if (entry.url.match(hashRegExp)) {
      delete entry.revision;
    }
    return entry;
  });
};
Parameters
manifestEntries Array.<ManifestEntry>

The full array of entries, prior to the current transformation.

Returns Array.<ManifestEntry>

The array of entries with the transformation applied.