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:
- Generate a complete service worker with precaching and some basic configurable options, writing the resulting service worker file to disk. See generateSW().
- Generate a complete service worker with precaching and some basic configurable options, without writing the results to disk. See generateSWString().
- 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().
- Just generate a manifest, not a full service worker file. This is useful if you want to make use of the manifest from your own existing service worker file and are okay with including the manifest yourself. See getManifest().
Methods
copyWorkboxLibraries
copyWorkboxLibraries(destDirectory) returns Promise containing string
This copies over a set of runtime libraries used by Workbox into a local directory, which should be deployed alongside your service worker file.
As an alternative to deploying these local copies, you could instead use Workbox from its official CDN URL.
This method is exposed for the benefit of developers using
injectManifest() who would prefer not to use the CDN copies of Workbox. Developers using
generateSW() don't need to explicitly call this method, as it's called automatically when
importWorkboxFrom
is set to local
.
Parameter |
|
---|---|
destDirectory |
string The path to the parent directory under which the new directory of libraries will be created. |
- Returns
-
Promise containing string
The name of the newly created directory.
generateSW
generateSW(config) returns Promise containing {count: Number, size: Number}
This method creates a list of URLs to precache, referred to as a "precache manifest", based on the options you provide.
It also takes in additional options that configures the service worker's behavior, like any runtimeCaching
rules it should use.
Based on the precache manifest and the additional configuration, it writes a ready-to-use service worker file to disk at swDest
.
Parameter |
|
---|---|
config |
- Returns
-
Promise containing {count: Number, size: Number}
A promise that resolves once the service worker file has been written toswDest
. Thesize
property contains the aggregate size of all the precached entries, in bytes, and thecount
property contains the total number of precached entries.
generateSWString
generateSWString(config) returns Promise containing String
This method generates a service worker based on the configuration options provided.
Parameter |
|
---|---|
config |
- Returns
-
Promise containing String
A populated service worker template, based on the other configuration options provided.
getManifest
getManifest(config) returns Promise containing {manifestEntries: Array of ManifestEntry, count: Number, size: Number}
This method returns a list of URLs to precache, referred to as a "precache manifest", along with details about the number of entries and their size, based on the options you provide.
Parameter |
|
---|---|
config |
- Returns
-
Promise containing {manifestEntries: Array of ManifestEntry, count: Number, size: Number}
A promise that resolves once the precache manifest is determined. Thesize
property contains the aggregate size of all the precached entries, in bytes, thecount
property contains the total number of precached entries, and themanifestEntries
property contains all theManifestEntry
items.
injectManifest
injectManifest(config) returns Promise containing {count: Number, size: Number}
This method creates a list of URLs to precache, referred to as a "precache manifest", based on the options you provide.
The manifest is injected into the swSrc
file, and the regular expression
injectionPointRegexp
determines where in the file the manifest should go.
The final service worker file, with the manifest injected, is written to disk at swDest
.
Parameter |
|
---|---|
config |
- Returns
-
Promise containing {count: Number, size: Number}
A promise that resolves once the service worker file has been written toswDest
. Thesize
property contains the aggregate size of all the precached entries, in bytes, and thecount
property contains the total number of precached entries.
Abstract types
Configuration
Object
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)
orworkboxBuild.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 tomodule.exports
. -
When using
workbox-webpack-plugin
within a Webpack build, pass the configuration object to the plugin's constructor, likenew 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
Parameter |
|
---|---|
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.: Note: This option is only valid when used with generateSW() or injectManifest(). |
swSrc |
String The path to the source service worker containing a E.g.: Note: This option is only valid when used with injectManifest(). |
swTemplate |
String A service worker template that should be populated based on the configuration provided. The template should be in a format that Note: This option is only valid when used with generateSWNoFS(). |
importWorkboxFromCDN |
Optional boolean If Note: This option is only valid when used with generateSW() or generateSWNoFS(). |
importScripts |
Optional Array of String An optional list of JavaScript files that should be passed to
Note: This option is only valid when used with generateSW() or generateSWNoFS(). |
globPatterns |
Optional Array of String Files matching against any of these glob patterns will be included in the precache manifest. E.g.: |
globDirectory |
String The base directory you wish to match E.g.: |
globIgnores |
Optional (String or Array of String) Files matching against any of these glob patterns will be excluded from the file manifest, overriding any matches from E.g. |
globFollow |
Optional Boolean Follow symlinked directories when expanding '**' patterns. Note that this can result in a lot of duplicate references in the presence of cyclic links. |
globStrict |
Optional Boolean When an unusual error is encountered when attempting to read a directory, the process will just continue on in search of other matches. Set the strict option to raise an error in these cases. |
templatedUrls |
Optional Object with (Array or string) properties 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.
|
maximumFileSizeToCacheInBytes |
Optional number 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 |
manifestTransforms |
Optional Array of ManifestTransform An array of manifest transformations, which will be applied sequentially against the generated manifest. If See ManifestTransform. |
modifyUrlPrefix |
Optional Object with String properties 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 E.g.
|
dontCacheBustUrlsMatching |
Optional RegExp 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 E.g. |
navigateFallback |
Optional String 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 E.g. |
navigateFallbackWhitelist |
Optional Array of RegExp 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 E.g. |
cacheId |
Optional String An optional ID to be prepended to caches used by 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 E.g. |
skipWaiting |
Optional Boolean 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 |
clientsClaim |
Optional Boolean 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 |
directoryIndex |
Optional string 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 |
runtimeCaching |
Optional Array of Object Passing in an array of objects containing Requests for precached URLs that are picked up via The 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
E.g.
|
ignoreUrlParametersMatching |
Optional Array of RegExp 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 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 E.g. |
handleFetch |
Optional Boolean Whether or not 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 |
ManifestEntry
Object
Properties
Parameter |
|
---|---|
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. |
ManifestTransform
ManifestTransform(manifestEntries) returns Array of 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.
Parameter |
|
---|---|
manifestEntries |
Array of ManifestEntry The full array of entries, prior to the current transformation. |
- Returns
-
Array of ManifestEntry
The array of entries with the transformation applied.
Examples
<caption>A transformation that prepended the origin of a CDN for any
URL starting with '/assets/' could be implemented as:</caption>
const cdnTransform = (manifestEntries) => manifestEntries.map(entry => {
const cdnOrigin = 'https://example.com';
if (entry.url.startsWith('/assets/')) {
entry.url = cdnOrigin + entry.url;
}
return entry;
});
<caption>A transformation that removes the revision field when the
URL contains an 8-character hash surrounded by '.', indicating that it
already contains revision information:</caption>
const removeRevisionTransform = (manifestEntries) => {
return manifestEntries.map(entry => {
const hashRegExp = /\.\w{8}\./;
if (entry.url.match(hashRegExp)) {
delete entry.revision;
}
return entry;
});
};