workbox-build
Summary
- Types
- Methods
Types
BasePartial
Properties
- additionalManifestEntries
(string | ManifestEntry)[] optional
A list of entries to be precached, in addition to any entries that are generated as part of the build configuration.
- dontCacheBustURLsMatching
RegExp optional
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. - manifestTransforms
ManifestTransform[] optional
One or more functions which will be applied sequentially against the generated manifest. If
modifyURLPrefix
ordontCacheBustURLsMatching
are also specified, their corresponding transformations will be applied first. - maximumFileSizeToCacheInBytes
number optional
Default value is: 2097152
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.
- modifyURLPrefix
object optional
An object mapping string prefixes to replacement string values. This can be used to, e.g., 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.Example usage:
// Replace a '/dist/' prefix with '/', and also prepend // '/static' to every URL. modifyURLPrefix: { '/dist/': '/', '': '/static', }
BuildResult
Type
Omit<GetManifestResult"manifestEntries"> & object
Properties
- filePaths
string[]
GeneratePartial
Properties
- babelPresetEnvTargets
string[] optional
Default value is: ["chrome >= 56"]
The targets to pass to
babel-preset-env
when transpiling the service worker bundle. - cacheId
string optional
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
boolean optional
Default value is: false
Whether or not Workbox should attempt to identify and delete any precaches created by older, incompatible versions.
- clientsClaim
boolean optional
Default value is: false
Whether or not the service worker should start controlling any existing clients as soon as it activates.
- directoryIndex
string optional
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. - disableDevLogs
boolean optional
Default value is: false
- ignoreURLParametersMatching
RegExp[] optional
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. If not provided, the default value is
[/^utm_/, /^fbclid$/]
. - importScripts
string[] optional
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
boolean optional
Default value is: false
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.
- mode
string optional
Default value is: "production"
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'
. string optional
Default value is: null
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.
RegExp[] optional
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 bothnavigateFallbackDenylist
andnavigateFallbackAllowlist
are configured, the denylist takes precedent.Note: These RegExps may be evaluated against every destination URL during a navigation. Avoid using complex RegExps, or else your users may see delays when navigating your site.
RegExp[] optional
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 bothnavigateFallbackDenylist
andnavigateFallbackAllowlist
are configured, the denylist takes precedence.Note: These RegExps may be evaluated against every destination URL during a navigation. Avoid using complex RegExps, or else your users may see delays when navigating your site.
boolean optional
Default value is: false
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
boolean | GoogleAnalyticsInitializeOptions optional
Default value is: false
Controls whether or not to include support for offline Google Analytics. When
true
, the call toworkbox-google-analytics
'sinitialize()
will be added to your generated service worker. When set to anObject
, that object will be passed in to theinitialize()
call, allowing you to customize the behavior. - runtimeCaching
RuntimeCaching[] optional
When using Workbox's build tools to generate your service worker, you can specify one or more runtime caching configurations. These are then translated to
workbox-routing.registerRoute
calls using the match and handler configuration you define.For all of the options, see the
workbox-build.RuntimeCaching
documentation. The example below shows a typical configuration, with two runtime routes defined: - skipWaiting
boolean optional
Default value is: false
Whether to add an unconditional call to
skipWaiting()
to the generated service worker. Iffalse
, then amessage
listener will be added instead, allowing client pages to triggerskipWaiting()
by callingpostMessage({type: 'SKIP_WAITING'})
on a waiting service worker. - sourcemap
boolean optional
Default value is: true
Whether to create a sourcemap for the generated service worker files.
GenerateSWOptions
Type
GetManifestOptions
GetManifestResult
Properties
- count
number
- manifestEntries
- size
number
- warnings
string[]
GlobPartial
Properties
- globFollow
boolean optional
Default value is: true
Determines whether or not symlinks are followed when generating the precache manifest. For more information, see the definition of
follow
in theglob
documentation. - globIgnores
string[] optional
Default value is: ["**\/node_modules\/**\/*"]
A set of patterns matching files to always exclude when generating the precache manifest. For more information, see the definition of
ignore
in theglob
documentation. - globPatterns
string[] optional
Default value is: ["**\/*.{js,css,html}"]
Files matching any of these patterns will be included in the precache manifest. For more information, see the
glob
primer. - globStrict
boolean optional
Default value is: true
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 theglob
documentation. - templatedURLs
object optional
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.
InjectManifestOptions
Type
InjectPartial
Properties
- injectionPoint
string optional
Default value is: "self.__WB_MANIFEST"
The string to find inside of the
swSrc
file. Once found, it will be replaced by the generated precache manifest. - 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.
ManifestEntry
Properties
- integrity
string optional
- revision
string
- url
string
ManifestTransform
workbox-build.ManifestTransform(
manifestEntries:
(ManifestEntry & object)[],
compilation?:
unknown,
)
Type
function
Parameters
- manifestEntries
(ManifestEntry & object)[]
- size
number
- compilation
unknown optional
Returns
Promise<ManifestTransformResult> | ManifestTransformResult
ManifestTransformResult
Properties
- manifest
(ManifestEntry & object)[]
- size
number
- warnings
string[] optional
OptionalGlobDirectoryPartial
Properties
- globDirectory
string optional
The local directory you wish to match
globPatterns
against. The path is relative to the current directory.
RequiredGlobDirectoryPartial
Properties
- globDirectory
string
The local directory you wish to match
globPatterns
against. The path is relative to the current directory.
RequiredSWDestPartial
Properties
- 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'.
RuntimeCaching
Properties
- handler
This determines how the runtime route will generate a response. To use one of the built-in
workbox-strategies
, provide its name, like'NetworkFirst'
. Alternatively, this can be aworkbox-core.RouteHandler
callback function with custom response logic. - method
HTTPMethod optional
Default value is: "GET"
The HTTP method to match against. The default value of
'GET'
is normally sufficient, unless you explicitly need to match'POST'
,'PUT'
, or another type of request. - options
object optional
- backgroundSync
object optional
Configuring this will add a
workbox-background-sync.BackgroundSyncPlugin
instance to theworkbox-strategies
configured inhandler
.- name
string
- options
QueueOptions optional
- broadcastUpdate
object optional
Configuring this will add a
workbox-broadcast-update.BroadcastUpdatePlugin
instance to theworkbox-strategies
configured inhandler
.- channelName
string optional
- options
- cacheName
string optional
If provided, this will set the
cacheName
property of theworkbox-strategies
configured inhandler
. - cacheableResponse
CacheableResponseOptions optional
Configuring this will add a
workbox-cacheable-response.CacheableResponsePlugin
instance to theworkbox-strategies
configured inhandler
. - expiration
ExpirationPluginOptions optional
Configuring this will add a
workbox-expiration.ExpirationPlugin
instance to theworkbox-strategies
configured inhandler
. - fetchOptions
RequestInit optional
Configuring this will pass along the
fetchOptions
value to theworkbox-strategies
configured inhandler
. - matchOptions
CacheQueryOptions optional
Configuring this will pass along the
matchOptions
value to theworkbox-strategies
configured inhandler
. - networkTimeoutSeconds
number optional
If provided, this will set the
networkTimeoutSeconds
property of theworkbox-strategies
configured inhandler
. Note that only'NetworkFirst'
and'NetworkOnly'
supportnetworkTimeoutSeconds
. - plugins
WorkboxPlugin[] optional
Configuring this allows the use of one or more Workbox plugins that don't have "shortcut" options (like
expiration
forworkbox-expiration.ExpirationPlugin
). The plugins provided here will be added to theworkbox-strategies
configured inhandler
. - precacheFallback
object optional
Configuring this will add a
workbox-precaching.PrecacheFallbackPlugin
instance to theworkbox-strategies
configured inhandler
.- fallbackURL
string
- rangeRequests
boolean optional
Enabling this will add a
workbox-range-requests.RangeRequestsPlugin
instance to theworkbox-strategies
configured inhandler
.
- urlPattern
string | RegExp | RouteMatchCallback
This match criteria determines whether the configured handler will generate a response for any requests that don't match one of the precached URLs. If multiple
RuntimeCaching
routes are defined, then the first one whoseurlPattern
matches will be the one that responds.This value directly maps to the first parameter passed to
workbox-routing.registerRoute
. It's recommended to use aworkbox-core.RouteMatchCallback
function for greatest flexibility.
StrategyName
Type
"CacheFirst"
,"CacheOnly"
,"NetworkFirst"
,"NetworkOnly"
, or"StaleWhileRevalidate"
WebpackGenerateSWOptions
WebpackGenerateSWPartial
Properties
- importScriptsViaChunks
string[] optional
One or more names of webpack chunks. The content of those chunks will be included in the generated service worker, via a call to
importScripts()
. - swDest
string optional
Default value is: "service-worker.js"
The asset name of the service worker file created by this plugin.
WebpackInjectManifestOptions
WebpackInjectManifestPartial
Properties
- compileSrc
boolean optional
Default value is: true
When
true
(the default), theswSrc
file will be compiled by webpack. Whenfalse
, compilation will not occur (andwebpackCompilationPlugins
can't be used.) Set tofalse
if you want to inject the manifest into, e.g., a JSON file. - swDest
string optional
The asset name of the service worker file that will be created by this plugin. If omitted, the name will be based on the
swSrc
name. - webpackCompilationPlugins
any[] optional
Optional
webpack
plugins that will be used when compiling theswSrc
input file. Only valid ifcompileSrc
istrue
.
WebpackPartial
Properties
- chunks
string[] optional
One or more chunk names whose corresponding output files should be included in the precache manifest.
- exclude
(string | RegExp | function)[] optional
One or more specifiers used to exclude assets from the precache manifest. This is interpreted following the same rules as
webpack
's standardexclude
option. If not provided, the default value is[/\.map$/, /^manifest.*\.js$]
. - excludeChunks
string[] optional
One or more chunk names whose corresponding output files should be excluded from the precache manifest.
- include
(string | RegExp | function)[] optional
One or more specifiers used to include assets in the precache manifest. This is interpreted following the same rules as
webpack
's standardinclude
option. - mode
string optional
If set to 'production', then an optimized service worker bundle that excludes debugging info will be produced. If not explicitly configured here, the
mode
value configured in the currentwebpack
compilation will be used.
Methods
copyWorkboxLibraries
workbox-build.copyWorkboxLibraries(
destDirectory:
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 workbox-build.injectManifest
who would prefer not to use the CDN copies of Workbox. Developers using workbox-build.generateSW
don't need to explicitly call this method.
Parameters
- destDirectory
string
The path to the parent directory under which the new directory of libraries will be created.
Returns
Promise<string>
The name of the newly created directory.
generateSW
workbox-build.generateSW(
config:
GenerateSWOptions,
)
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
.
// The following lists some common options; see the rest of the documentation
// for the full set of options and defaults.
const {count, size, warnings} = await generateSW({
dontCacheBustURLsMatching: [new RegExp('...')],
globDirectory: '...',
globPatterns: ['...', '...'],
maximumFileSizeToCacheInBytes: ...,
navigateFallback: '...',
runtimeCaching: [{
// Routing via a matchCallback function:
urlPattern: ({request, url}) => ...,
handler: '...',
options: {
cacheName: '...',
expiration: {
maxEntries: ...,
},
},
}, {
// Routing via a RegExp:
urlPattern: new RegExp('...'),
handler: '...',
options: {
cacheName: '...',
plugins: [..., ...],
},
}],
skipWaiting: ...,
swDest: '...',
});
Parameters
- config
Returns
Promise<BuildResult>
getManifest
workbox-build.getManifest(
config:
GetManifestOptions,
)
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.
// The following lists some common options; see the rest of the documentation
// for the full set of options and defaults.
const {count, manifestEntries, size, warnings} = await getManifest({
dontCacheBustURLsMatching: [new RegExp('...')],
globDirectory: '...',
globPatterns: ['...', '...'],
maximumFileSizeToCacheInBytes: ...,
});
Parameters
- config
Returns
Promise<GetManifestResult>
getModuleURL
workbox-build.getModuleURL(
moduleName:
string,
buildType:
BuildType,
)
Parameters
- moduleName
string
- buildType
BuildType
Returns
string
injectManifest
workbox-build.injectManifest(
config:
InjectManifestOptions,
)
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
.
This method will not compile or bundle your swSrc
file; it just handles injecting the manifest.
// The following lists some common options; see the rest of the documentation
// for the full set of options and defaults.
const {count, size, warnings} = await injectManifest({
dontCacheBustURLsMatching: [new RegExp('...')],
globDirectory: '...',
globPatterns: ['...', '...'],
maximumFileSizeToCacheInBytes: ...,
swDest: '...',
swSrc: '...',
});
Parameters
- config
Returns
Promise<BuildResult>