Stay organized with collections Save and categorize content based on your preferences.
The workbox-build
module integrates into a node-based build process and can generate an entire service worker, or just generate a list of assets to precache that could be used within an existing service worker.
The two modes that most developers will use are generateSW
and injectManifest
. The answers to the following questions can help you choose the right mode and configuration to use.
generateSW
The generateSW
mode creates a service worker file for you, customized via configuration options, and writes it out to disk.
generateSW
generateSW
injectManifest
The injectManifest
mode will generate a list of URLs to precache, and add that precache manifest to an existing service worker file. It will otherwise leave the file as-is.
injectManifest
injectManifest
generateSW
Mode
You can use the generateSW
mode within a node-based build script, using the most common configuration options, like so:
// Inside of build.js:
const {generateSW} = require('workbox-build');
// These are some common options, and not all are required.
// Consult the docs for more info.
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: '...',
}).then(({count, size, warnings}) => {
if (warnings.length > 0) {
console.warn(
'Warnings encountered while generating a service worker:',
warnings.join('\n')
);
}
console.log(`Generated a service worker, which will precache ${count} files, totaling ${size} bytes.`);
});
This will generate a service worker with precaching setup for all of the files picked up by your configuration, and the runtime caching rules provided.
A full set of configuration options can be found in the reference documentation.
injectManifest
Mode
You can use the injectManifest
mode within a node-based build script, using the most common configuration options, like so:
// Inside of build.js:
const {injectManifest} = require('workbox-build');
// These are some common options, and not all are required.
// Consult the docs for more info.
injectManifest({
dontCacheBustURLsMatching: [new RegExp('...')],
globDirectory: '...',
globPatterns: ['...', '...'],
maximumFileSizeToCacheInBytes: ...,
swDest: '...',
swSrc: '...',
}).then(({count, size, warnings}) => {
if (warnings.length > 0) {
console.warn(
'Warnings encountered while injecting the manifest:',
warnings.join('\n')
);
}
console.log(`Injected a manifest which will precache ${count} files, totaling ${size} bytes.`);
});
This will create a precache manifest based on the files picked up by your configuration and inject it into your existing service worker file.
A full set of configuration options can be found in the reference documentation.
Additional modesWe expect that generateSW
or injectManifest
will suit most developers' needs. However, there is one other mode supported by workbox-build
that might be appropriate for certain use cases.
getManifest
Mode
This is conceptually similar to the injectManifest
mode, but instead of adding the manifest into the source service worker file, it returns the array of manifest entries, along with information about the number of entries and total size.
You can use the injectManifest
mode within a node-based build script, using the most common configuration options, like so:
// Inside of build.js:
const {getManifest} = require('workbox-build');
// These are some common options, and not all are required.
// Consult the docs for more info.
getManifest({
dontCacheBustURLsMatching: [new RegExp('...')],
globDirectory: '...',
globPatterns: ['...', '...'],
maximumFileSizeToCacheInBytes: ...,
}).then(({manifestEntries, count, size, warnings}) => {
if (warnings.length > 0) {
console.warn(
'Warnings encountered while getting the manifest:',
warnings.join('\n')
);
}
// Do something with the manifestEntries, and potentially log count and size.
});
A full set of configuration options can be found in the reference documentation.
Types PropertiesA 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.
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
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',
}
babelPresetEnvTargets
string[] optional
Default value is: ["chrome >= 56"]
The targets to pass to babel-preset-env
when transpiling the service worker bundle.
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'
.
navigateFallback
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.
navigateFallbackAllowlist
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 both navigateFallbackDenylist
and navigateFallbackAllowlist
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.
navigateFallbackDenylist
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 both navigateFallbackDenylist
and navigateFallbackAllowlist
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.
navigationPreload
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.
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.
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. If false
, then a message
listener will be added instead, allowing client pages to trigger skipWaiting()
by calling postMessage({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.
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 the glob
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 the glob
documentation.
globPatterns
string[] optional
Default value is: ["**\/*.{js,wasm,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 the glob
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.
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.
The path and filename of the service worker file that will be read during the build process, relative to the current working directory.
integrity
string optional
compilation
unknown optional
warnings
string[] optional
globDirectory
string optional
The local directory you wish to match globPatterns
against. The path is relative to the current directory.
The local directory you wish to match globPatterns
against. The path is relative to the current directory.
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'.
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 a workbox-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.
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 whose urlPattern
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 a workbox-core.RouteMatchCallback
function for greatest flexibility.
"CacheFirst"
"CacheOnly"
"NetworkFirst"
"NetworkOnly"
"StaleWhileRevalidate"
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.
compileSrc
boolean optional
Default value is: true
When true
(the default), the swSrc
file will be compiled by webpack. When false
, compilation will not occur (and webpackCompilationPlugins
can't be used.) Set to false
if you want to inject the manifest into, e.g., a JSON file.
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 the swSrc
input file. Only valid if compileSrc
is true
.
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 standard exclude
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 standard include
option.
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 current webpack
compilation will be used.
workbox-build.copyWorkboxLibraries(
destDirectory: string,
): Promise<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.
The path to the parent directory under which the new directory of libraries will be created.
The name of the newly created directory.
workbox-build.generateSW(
config: GenerateSWOptions,
): Promise<BuildResult>
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: '...',
});
getManifest()
workbox-build.getManifest(
config: GetManifestOptions,
): Promise<GetManifestResult>
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: ...,
});
getModuleURL()
workbox-build.getModuleURL(injectManifest()
moduleName: string,
buildType: BuildType,
): string
workbox-build.injectManifest(
config: InjectManifestOptions,
): Promise<BuildResult>
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: '...',
});
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2018-01-31 UTC.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2018-01-31 UTC."],[],[]]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4