web.dev LIVE is now over! Head to web.dev/live to watch all the sessions, see top Q&A, and more.

Module: workbox-build

Methods

copyWorkboxLibraries

static

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.

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

async   static

generateSW(config) returns Promise containing {count: number, filePaths: Array of string, size: number, warnings: Array of string}

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

Object

The configuration to use.

Values in config have the following properties:

Parameter

globDirectory

string

The local directory you wish to match globPatterns against. The path is relative to the current directory.

swDest

string

The path and filename of the service worker file that will be created by the build process, relative to the current working directory. It must end in '.js'.

additionalManifestEntries

Optional

Array of module:workbox-build.ManifestEntry

A list of entries to be precached, in addition to any entries that are generated as part of the build configuration.

babelPresetEnvTargets

Optional

Array of string

The targets to pass to babel-preset-env when transpiling the service worker bundle.

cacheId

Optional

string

An optional ID to be prepended to cache names. This is primarily useful for local development where multiple sites may be served from the same http://localhost:port origin.

cleanupOutdatedCaches

Optional

boolean

Whether or not Workbox should attempt to identify an delete any precaches created by older, incompatible versions.

clientsClaim

Optional

boolean

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

directoryIndex

Optional

string

If a navigation request for a URL ending in / fails to match a precached URL, this value will be appended to the URL and that will be checked for a precache match. This should be set to what your web server is using for its directory index.

dontCacheBustURLsMatching

Optional

RegExp

Assets that match this will be assumed to be uniquely versioned via their URL, and 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 that, as it will reduce the bandwidth consumed when precaching.

globFollow

Optional

boolean

Determines whether or not symlinks are followed when generating the precache manifest. For more information, see the definition of follow in the glob documentation.

globIgnores

Optional

Array of string

A set of patterns matching files to always exclude when generating the precache manifest. For more information, see the definition of ignore in the glob documentation.

globPatterns

Optional

Array of string

Files matching any of these patterns will be included in the precache manifest. For more information, see the glob primer.

globStrict

Optional

boolean

If true, an error reading a directory when generating a precache manifest will cause the build to fail. If false, the problematic directory will be skipped. For more information, see the definition of strict in the glob documentation.

ignoreURLParametersMatching

Optional

Array of RegExp

Any search parameter names that match against one of the RegExp 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.

importScripts

Optional

Array of string

A list of JavaScript files that should be passed to importScripts() inside the generated service worker file. This is useful when you want to let Workbox create your top-level service worker file, but want to include some additional code, such as a push event listener.

inlineWorkboxRuntime

Optional

boolean

Whether the runtime code for the Workbox library should be included in the top-level service worker, or split into a separate file that needs to be deployed alongside the service worker. Keeping the runtime separate means that users will not have to re-download the Workbox code each time your top-level service worker changes.

manifestTransforms

Optional

Array of module:workbox-build.ManifestTransform

One or more functions which will be applied sequentially against the generated manifest. If modifyURLPrefix or dontCacheBustURLsMatching are also specified, their corresponding transformations will be applied first.

maximumFileSizeToCacheInBytes

Optional

number

This value can be used to determine the maximum size of files that will be precached. This prevents you from inadvertently precaching very large files that might have accidentally matched one of your patterns.

mode

Optional

string

If set to 'production', then an optimized service worker bundle that excludes debugging info will be produced. If not explicitly configured here, the process.env.NODE_ENV value will be used, and failing that, it will fall back to 'production'.

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 manifestTransforms option and provide a function that modifies the entries in the manifest using whatever logic you provide.

navigateFallback

Optional

string

If specified, all navigation requests for URLs that aren't precached will be fulfilled with the HTML at the URL provided. You must pass in the URL of an HTML document that is listed in your precache manifest. This is meant to be used in a Single Page App scenario, in which you want all navigations to use common App Shell HTML.

navigateFallbackDenylist

Optional

Array of RegExp

An optional array of regular expressions that restricts which URLs the configured navigateFallback behavior applies to. This is useful if only a subset of your site's URLs should be treated as being part of a Single Page App. If both navigateFallbackDenylist and navigateFallbackAllowlist are configured, the denylist takes precedent.

navigateFallbackAllowlist

Optional

Array of RegExp

An optional array of regular expressions that restricts which URLs the configured navigateFallback behavior applies to. This is useful if only a subset of your site's URLs should be treated as being part of a Single Page App. If both navigateFallbackDenylist and navigateFallbackAllowlist are configured, the denylist takes precedent.

navigationPreload

Optional

boolean

Whether or not to enable navigation preload in the generated service worker. When set to true, you must also use runtimeCaching to set up an appropriate response strategy that will match navigation requests, and make use of the preloaded response.

offlineGoogleAnalytics

Optional

(boolean or Object)

Controls whether or not to include support for offline Google Analytics. When true, the call to workbox-google-analytics's initialize() will be added to your generated service worker. When set to an Object, that object will be passed in to the initialize() call, allowing you to customize the behavior.

runtimeCaching

Optional

Array of RuntimeCachingEntry

skipWaiting

Optional

boolean

Whether to add an unconditional call to skipWaiting() to the generated service worker. If false, then a message listener will be added instead, allowing you to conditionally call skipWaiting().

sourcemap

Optional

boolean

Whether to create a sourcemap for the generated service worker files.

templatedURLs

Optional

Object

If a URL is rendered based on some server-side logic, its contents may depend on multiple files or on some other unique string value. The keys in this object are server-rendered URLs. If the values are 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 for a given URL.

Returns

Promise containing {count: number, filePaths: Array of string, size: number, warnings: Array of string} A promise that resolves once the service worker and related files (indicated by filePaths) has been written to swDest. The size property contains the aggregate size of all the precached entries, in bytes, and the count property contains the total number of precached entries. Any non-fatal warning messages will be returned via warnings.

getManifest

async   static

getManifest(config) returns Promise containing {count: number, filePaths: Array of string, size: number, warnings: Array of string}

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

Object

The configuration to use.

Values in config have the following properties:

Parameter

globDirectory

string

The local directory you wish to match globPatterns against. The path is relative to the current directory.

additionalManifestEntries

Optional

Array of module:workbox-build.ManifestEntry

A list of entries to be precached, in addition to any entries that are generated as part of the build configuration.

dontCacheBustURLsMatching

Optional

RegExp

Assets that match this will be assumed to be uniquely versioned via their URL, and 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 that, as it will reduce the bandwidth consumed when precaching.

globFollow

Optional

boolean

Determines whether or not symlinks are followed when generating the precache manifest. For more information, see the definition of follow in the glob documentation.

globIgnores

Optional

Array of string

A set of patterns matching files to always exclude when generating the precache manifest. For more information, see the definition of ignore in the glob documentation.

globPatterns

Optional

Array of string

Files matching any of these patterns will be included in the precache manifest. For more information, see the glob primer.

globStrict

Optional

boolean

If true, an error reading a directory when generating a precache manifest will cause the build to fail. If false, the problematic directory will be skipped. For more information, see the definition of strict in the glob documentation.

manifestTransforms

Optional

Array of module:workbox-build.ManifestTransform

One or more functions which will be applied sequentially against the generated manifest. If modifyURLPrefix or dontCacheBustURLsMatching are also specified, their corresponding transformations will be applied first.

maximumFileSizeToCacheInBytes

Optional

number

This value can be used to determine the maximum size of files that will be precached. This prevents you from inadvertently precaching very large files that might have accidentally matched one of your patterns.

mode

Optional

string

If set to 'production', then an optimized service worker bundle that excludes debugging info will be produced. If not explicitly configured here, the process.env.NODE_ENV value will be used, and failing that, it will fall back to 'production'.

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 manifestTransforms option and provide a function that modifies the entries in the manifest using whatever logic you provide.

templatedURLs

Optional

Object

If a URL is rendered based on some server-side logic, its contents may depend on multiple files or on some other unique string value. The keys in this object are server-rendered URLs. If the values are 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 for a given URL.

Returns

Promise containing {count: number, filePaths: Array of string, size: number, warnings: Array of string} A promise that resolves once the service worker and related files (indicated by filePaths) has been written to swDest. The size property contains the aggregate size of all the precached entries, in bytes, and the count property contains the total number of precached entries. Any non-fatal warning messages will be returned via warnings.

injectManifest

async   static

injectManifest(config) returns Promise containing {count: number, filePaths: Array of string, size: number, warnings: Array of string}

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 placeholder string injectionPoint 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

Object

The configuration to use.

Values in config have the following properties:

Parameter

globDirectory

string

The local directory you wish to match globPatterns against. The path is relative to the current directory.

swDest

string

The path and filename of the service worker file that will be created by the build process, relative to the current working directory. It must end in '.js'.

swSrc

string

The path and filename of the service worker file that will be read during the build process, relative to the current working directory.

additionalManifestEntries

Optional

Array of module:workbox-build.ManifestEntry

A list of entries to be precached, in addition to any entries that are generated as part of the build configuration.

dontCacheBustURLsMatching

Optional

RegExp

Assets that match this will be assumed to be uniquely versioned via their URL, and 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 that, as it will reduce the bandwidth consumed when precaching.

globFollow

Optional

boolean

Determines whether or not symlinks are followed when generating the precache manifest. For more information, see the definition of follow in the glob documentation.

globIgnores

Optional

Array of string

A set of patterns matching files to always exclude when generating the precache manifest. For more information, see the definition of ignore in the glob documentation.

globPatterns

Optional

Array of string

Files matching any of these patterns will be included in the precache manifest. For more information, see the glob primer.

globStrict

Optional

boolean

If true, an error reading a directory when generating a precache manifest will cause the build to fail. If false, the problematic directory will be skipped. For more information, see the definition of strict in the glob documentation.

injectionPoint

Optional

string

The string to find inside of the swSrc file. Once found, it will be replaced by the generated precache manifest.

manifestTransforms

Optional

Array of module:workbox-build.ManifestTransform

One or more functions which will be applied sequentially against the generated manifest. If modifyURLPrefix or dontCacheBustURLsMatching are also specified, their corresponding transformations will be applied first.

maximumFileSizeToCacheInBytes

Optional

number

This value can be used to determine the maximum size of files that will be precached. This prevents you from inadvertently precaching very large files that might have accidentally matched one of your patterns.

mode

Optional

string

If set to 'production', then an optimized service worker bundle that excludes debugging info will be produced. If not explicitly configured here, the process.env.NODE_ENV value will be used, and failing that, it will fall back to 'production'.

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 manifestTransforms option and provide a function that modifies the entries in the manifest using whatever logic you provide.

templatedURLs

Optional

Object

If a URL is rendered based on some server-side logic, its contents may depend on multiple files or on some other unique string value. The keys in this object are server-rendered URLs. If the values are 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 for a given URL.

Returns

Promise containing {count: number, filePaths: Array of string, size: number, warnings: Array of string} A promise that resolves once the service worker and related files (indicated by filePaths) has been written to swDest. The size property contains the aggregate size of all the precached entries, in bytes, and the count property contains the total number of precached entries. Any non-fatal warning messages will be returned via warnings.

Abstract types

ManifestEntry

static

Object

Properties

Parameter

url

string

The URL to the asset in the manifest.

revision

Optional

string

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

integrity

Optional

string

Integrity metadata that will be used when making the network request for the URL.

ManifestTransform

static

ManifestTransform(manifestEntries, compilation) returns Promise containing module:workbox-build.ManifestTransformResult

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 module:workbox-build.ManifestEntry

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

compilation

Optional

Object

When used in the webpack plugins, this param will be set to the current compilation.

Returns

Promise containing module:workbox-build.ManifestTransformResult The array of entries with the transformation applied, and optionally, any warnings that should be reported back to the build tool.

Examples

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

const cdnTransform = async (manifestEntries) => {
  const manifest = manifestEntries.map(entry => {
    const cdnOrigin = 'https://example.com';
    if (entry.url.startsWith('/assets/')) {
      entry.url = cdnOrigin + entry.url;
    }
    return entry;
  });
  return {manifest, warnings: []};
};
A transformation that nulls the revision field when the
URL contains an 8-character hash surrounded by '.', indicating that it
already contains revision information:

const removeRevisionTransform = async (manifestEntries) => {
  const manifest = manifestEntries.map(entry => {
    const hashRegExp = /\.\w{8}\./;
    if (entry.url.match(hashRegExp)) {
      entry.revision = null;
    }
    return entry;
  });
  return {manifest, warnings: []};
};

ManifestTransformResult

static

Object

Properties

Parameter

manifest

Array of module:workbox-build.ManifestEntry

warnings

(Array of string or undefined)

RuntimeCachingEntry

static

Object

Properties

Parameter

handler

(string or module:workbox-routing~handlerCallback)

Either the name of one of the built-in strategy classes, or custom handler callback to use when the generated route matches.

urlPattern

(string, RegExp, or module:workbox-routing~matchCallback)

The value that will be passed to registerRoute(), used to determine whether the generated route will match a given request.

method

Optional

string

The HTTP method that will match the generated route.

options

Optional

Object

Values in options have the following properties:

Parameter

backgroundSync

Optional

Object

backgroundSync.name

Optional

string

The name property to use when creating the BackgroundSyncPlugin.

backgroundSync.options

Optional

Object

The options property to use when creating the BackgroundSyncPlugin.

broadcastUpdate

Optional

Object

broadcastUpdate.channelName

Optional

string

The channelName property to use when creating the BroadcastCacheUpdatePlugin.

broadcastUpdate.options

Optional

Object

The options property to use when creating the BroadcastCacheUpdatePlugin.

cacheableResponse

Optional

Object

cacheableResponse.headers

Optional

Object

The headers property to use when creating the CacheableResponsePlugin.

cacheableResponse.statuses

Optional

Array of number

statuses property to use when creating the CacheableResponsePlugin.

cacheName

Optional

string

The cacheName to use when constructing one of the Workbox strategy classes.

fetchOptions

Optional

Object

The fetchOptions property value to use when constructing one of the Workbox strategy classes.

expiration

Optional

Object

expiration.maxAgeSeconds

Optional

number

The maxAgeSeconds property to use when creating the ExpirationPlugin.

expiration.maxEntries

Optional

number

The maxAgeSeconds property to use when creating the ExpirationPlugin.

matchOptions

Optional

Object

The matchOptions property value to use when constructing one of the Workbox strategy classes.

networkTimeoutSeconds

Optional

number

The networkTimeoutSeconds property value to use when creating a NetworkFirst strategy.

plugins

Optional

Array of Object

One or more additional plugins to apply to the handler. Useful when you want a plugin that doesn't have a "shortcut" configuration.