Chrome Dev Summit 2018 is happening now and streaming live on YouTube. Watch now.

Workbox Build

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.

Which Mode to Use

generateSW

The generateSW mode creates a service worker file for you, and writes it out to disk.

When to use generateSW

  • You want to precache files.
  • You have simple runtime configuration needs (e.g. the configuration allows you to define routes and strategies).

When NOT to use generateSW

  • You want to use other Service Worker features (i.e. Web Push).
  • You want to import additional scripts or add additional logic.

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.

When to use injectManifest

  • You want more control over your service worker.
  • You want to precache files.
  • You have more complex needs in terms of routing.
  • You would like to use your service worker with other API's (e.g. Web Push).

When NOT to use injectManifest

  • You want the easiest path to adding a service worker to your site.

generateSW Mode

You can use the generateSW mode within a node-based build script like so:

// Inside of build.js:
const {generateSW} = require('workbox-build');

const swDest = 'build/sw.js';
generateSW({
  swDest,
  // Other configuration options...
}).then(({count, size}) => {
  console.log(`Generated ${swDest}, 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.

Full generateSW Config

swDest

Required String

The path and filename of the service worker file that will be created by the build process. In node, this will be relative to the current working directory. In webpack, this will be relative to the webpack output directory.

Example:

swDest: path.join('dist', 'sw.js')

importWorkboxFrom

Optional String, defaulting to 'cdn'

Valid values are 'cdn', 'local', and 'disabled.

  • 'cdn', the default, will use a URL for the Workbox runtime libraries hosted on a highly-available Google Cloud Storage instance.
  • 'local' will copy all of the Workbox runtime libraries into a versioned directory alongside your generated service worker, and configure the service worker to use those local copies. This option is provided for developers who would prefer to host everything themselves and not rely on the Google Cloud Storage CDN.
  • 'disabled' will opt-out automatic behavior. It's up to you to host a local copy of the Workbox libraries at your preferred URL, and to pass in the correct path to workbox-sw.js via the importScripts configuration option.
  • Note: In webpack, passing in a string corresponding to the webpack chunk name containing a custom Workbox runtime library bundle is also supported.

Example:

importWorkboxFrom: 'local'

skipWaiting

Optional Boolean, defaulting to false

Whether or not the service worker should skip over the waiting lifecycle stage. Normally this is used with `clientsClaim: true`.

Example:

skipWaiting: true

clientsClaim

Optional Boolean, defaulting to false

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

Example:

clientsClaim: true

runtimeCaching

Optional Array of Object, defaulting to []

Passing in an array of objects containing urlPatterns, handlers, and potentially options 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 accommodated in runtimeCaching.

The handler values are strings, corresponding to names of the strategies supported by workbox.strategies.

The options properties can be used to configure instances of the cache expiration, cacheable response, and broadcast cache update plugins to apply to a given route.

Example:

runtimeCaching: [{
    // Match any same-origin request that contains 'api'.
    urlPattern: /api/,
    // Apply a network-first strategy.
    handler: 'networkFirst',
    options: {
      // Fall back to the cache after 10 seconds.
      networkTimeoutSeconds: 10,
      // Use a custom cache name for this route.
      cacheName: 'my-api-cache',
      // Configure custom cache expiration.
      expiration: {
        maxEntries: 5,
        maxAgeSeconds: 60,
      },
      // Configure background sync.
      backgroundSync: {
        name: 'my-queue-name',
        options: {
          maxRetentionTime: 60 * 60,
        },
      },
      // Configure which responses are considered cacheable.
      cacheableResponse: {
        statuses: [0, 200],
        headers: {'x-test': 'true'},
      },
      // Configure the broadcast cache update plugin.
      broadcastUpdate: {
        channelName: 'my-update-channel',
      },
      // Add in any additional plugin logic you need.
      plugins: [
        {cacheDidUpdate: () => /* custom plugin code */}
      ],
      // matchOptions and fetchOptions are used to configure the handler.
      fetchOptions: {
        mode: 'no-cors',
      },
      matchOptions: {
        ignoreSearch: true,
      },
    },
  }, {
    // To match cross-origin requests, use a RegExp that matches
    // the start of the origin:
    urlPattern: new RegExp('^https://cors\.example\.com/'),
    handler: 'staleWhileRevalidate',
    options: {
      cacheableResponse: {
        statuses: [0, 200]
      }
    }
  }]

navigateFallback

Optional String, defaulting to undefined

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 use common App Shell HTML.

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

Example:

navigateFallback: '/app-shell'

navigateFallbackBlacklist

Optional Array of RegExp, defaulting to []

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 navigateFallbackBlacklist and navigateFallbackWhitelist are configured, the blacklist takes precedent.

Example:

// Exempt all URLs that start with /_ or contain admin anywhere:
navigateFallbackBlacklist: [/^\/_/, /admin/]

navigateFallbackWhitelist

Optional Array of RegExp, defaulting to []

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 navigateFallbackBlacklist and navigateFallbackWhitelist are configured, the blacklist takes precedent.

Example:

// Include URLs that start with /pages:
navigateFallbackWhitelist: [/^\/pages/]

importScripts

Required Array of String

An required list of JavaScript files that should be passed to importScripts() inside the generated service worker file.

If one of the imported files sets the self.__precacheManifest variable to an array of ManifestEntrys, those entries will be automatically precached in the generated service worker.

This is also 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.

Example:

importScripts: ['push-notifications.abcd1234.js']

ignoreUrlParametersMatching

Optional Array of RegExp, defaulting to [/^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.

Example:

// This will ignore all parameters:
ignoreUrlParametersMatching: [/./]

directoryIndex

Optional String, defaulting to index.html

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 configured to whatever your web server is using, if anything, for its directory index.

Example:

directoryIndex: 'index.html'

cacheId

Optional String, defaulting to null

An optional ID to be prepended to cache names used by Workbox.

This is primarily useful for local development where multiple sites may be served from the same http://localhost:port origin.

Example:

cacheId: 'my-app'

offlineGoogleAnalytics

Optional Boolean, defaulting to false

Controls whether or not to include support for offline Google Analytics.

When true, workbox.googleAnalytics.initialize() will be added to your new service worker file.

Example:

offlineGoogleAnalytics: true

globDirectory

Optional String, defaulting to undefined

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

If you do set this, make sure to also configure globPatterns.

Example:

// Treat all patterns as relative to the current directory:
globDirectory: '.'

globFollow

Optional Boolean, defaulting to 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.

Example:

globFollow: false

globIgnores

Optional Array of String, defaulting to ['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.

Example:

globIgnores: ['**/ignored.html']

globPatterns

Optional Array of String, defaulting to either ['**/*.{js,css,html}'] (for workbox-build and workbox-cli) or [] (for workbox-webpack-plugin)

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

For more information, see the glob primer.

Note: Setting globPatterns is often unnecessary when using the workbox-webpack-plugin, which will automatically precache files that are part of the webpack build pipeline by default. When using the webpack plugin, only set it when you need to cache non-webpack assets.

Example:

globPatterns: ['dist/*.{js,png,html,css}']

globStrict

Optional Boolean, defaulting to 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.

Example:

globStrict: false

templatedUrls

Optional Object with String or Array of String values, defaulting to null

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.

Example:

templatedUrls: {
  '/app-shell': [
    'dev/templates/app-shell.hbs',
    'dev/**/*.css',
    ],
  '/other-page': 'my-version-info',
}

maximumFileSizeToCacheInBytes

Optional Number, defaulting to 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 accidentally matched one of your patterns.

Example:

// Increase the limit to 4mb:
maximumFileSizeToCacheInBytes: 4 * 1024 * 1024

dontCacheBustUrlsMatching

Optional RegExp, defaulting to null

Assets that match this regex 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 those values, as it will reduce the amount of bandwidth consumed when precaching.

Example:

dontCacheBustUrlsMatching: /\.\w{8}\./

modifyUrlPrefix

Optional Object with String values, defaulting to null

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.

Example:

modifyUrlPrefix: {
  // Remove a '/dist' prefix from the URLs:
  '/dist': ''
}

manifestTransforms

Optional Array of ManifestTransform, defaulting to null

One or more ManifestTransform functions, which will be applied sequentially against the generated manifest.

If modifyUrlPrefix or dontCacheBustUrlsMatching are also specified, their corresponding transformations will be applied first.

Example:

manifestTransforms: [
  // Basic transformation to remove a certain URL:
  (originalManifest) => {
    const manifest = originalManifest.filter(
      (entry) => entry.url !== 'ignored.html');
    // Optionally, set warning messages.
    const warnings = []; 
    return {manifest, warnings};
  }
]

injectManifest Mode

You can use the injectManifest mode within a node-based build script like so:

// Inside of build.js:
const {injectManifest} = require('workbox-build');

const swSrc = 'src/sw.js';
const swDest = 'build/sw.js';
injectManifest({
  swSrc,
  swDest,
  // Other configuration options...
}).then(({count, size}) => {
  console.log(`Generated ${swDest}, 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.

Full injectManifest Config

swDest

Required String

The path and filename of the service worker file that will be created by the build process. In node, this will be relative to the current working directory. In webpack, this will be relative to the webpack output directory.

Example:

swDest: path.join('dist', 'sw.js')

swSrc

Required String

The path to the source service worker file that can contain your own customized code, in addition to containing a match for injectionPointRegexp.

In Node

Your service worker file should include a call to a workbox.precaching method that makes use of the injected precache manifest.

In Webpack

Your service worker file should reference the self.__precacheManifest variable to obtain a list of ManifestEntrys obtained as part of the compilation: workbox.precaching.precacheAndRoute(self.__precacheManifest)

Example:

swDest: path.join('src', 'sw.js')

globDirectory

Optional String, defaulting to undefined

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

If you do set this, make sure to also configure globPatterns.

Example:

// Treat all patterns as relative to the current directory:
globDirectory: '.'

globFollow

Optional Boolean, defaulting to 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.

Example:

globFollow: false

globIgnores

Optional Array of String, defaulting to ['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.

Example:

globIgnores: ['**/ignored.html']

globPatterns

Optional Array of String, defaulting to either ['**/*.{js,css,html}'] (for workbox-build and workbox-cli) or [] (for workbox-webpack-plugin)

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

For more information, see the glob primer.

Note: Setting globPatterns is often unnecessary when using the workbox-webpack-plugin, which will automatically precache files that are part of the webpack build pipeline by default. When using the webpack plugin, only set it when you need to cache non-webpack assets.

Example:

globPatterns: ['dist/*.{js,png,html,css}']

globStrict

Optional Boolean, defaulting to 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.

Example:

globStrict: false

templatedUrls

Optional Object with String or Array of String values, defaulting to null

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.

Example:

templatedUrls: {
  '/app-shell': [
    'dev/templates/app-shell.hbs',
    'dev/**/*.css',
    ],
  '/other-page': 'my-version-info',
}

maximumFileSizeToCacheInBytes

Optional Number, defaulting to 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 accidentally matched one of your patterns.

Example:

// Increase the limit to 4mb:
maximumFileSizeToCacheInBytes: 4 * 1024 * 1024

dontCacheBustUrlsMatching

Optional RegExp, defaulting to null

Assets that match this regex 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 those values, as it will reduce the amount of bandwidth consumed when precaching.

Example:

dontCacheBustUrlsMatching: /\.\w{8}\./

modifyUrlPrefix

Optional Object with String values, defaulting to null

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.

Example:

modifyUrlPrefix: {
  // Remove a '/dist' prefix from the URLs:
  '/dist': ''
}

manifestTransforms

Optional Array of ManifestTransform, defaulting to null

One or more ManifestTransform functions, which will be applied sequentially against the generated manifest.

If modifyUrlPrefix or dontCacheBustUrlsMatching are also specified, their corresponding transformations will be applied first.

Example:

manifestTransforms: [
  // Basic transformation to remove a certain URL:
  (originalManifest) => {
    const manifest = originalManifest.filter(
      (entry) => entry.url !== 'ignored.html');
    // Optionally, set warning messages.
    const warnings = []; 
    return {manifest, warnings};
  }
]

Additional modes

We expect that generateSW or injectManifest will suit most developers' needs. However, there are two other modes supported by workbox-build that might be appropriate for certain use cases.

generateSWString Mode

This is conceptually similar to the generateSW mode, but instead of writing the generated service worker file to disk, it returns the contents of the service worker as a string.

You can use the generateSWSring mode within a node-based build script like so:

// Inside of build.js:
const {generateSWString} = require('workbox-build');

generateSWString({
  // Configuration options...
}).then((swString) => {
  // Do something with the generated code in swString.
});

The supported configuration options are:

globDirectory

Optional String, defaulting to undefined

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

If you do set this, make sure to also configure globPatterns.

Example:

// Treat all patterns as relative to the current directory:
globDirectory: '.'

globPatterns

Optional Array of String, defaulting to either ['**/*.{js,css,html}'] (for workbox-build and workbox-cli) or [] (for workbox-webpack-plugin)

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

For more information, see the glob primer.

Note: Setting globPatterns is often unnecessary when using the workbox-webpack-plugin, which will automatically precache files that are part of the webpack build pipeline by default. When using the webpack plugin, only set it when you need to cache non-webpack assets.

Example:

globPatterns: ['dist/*.{js,png,html,css}']

importScripts

Required Array of String

An required list of JavaScript files that should be passed to importScripts() inside the generated service worker file.

If one of the imported files sets the self.__precacheManifest variable to an array of ManifestEntrys, those entries will be automatically precached in the generated service worker.

This is also 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.

Example:

importScripts: ['push-notifications.abcd1234.js']

importWorkboxFrom

Optional String, defaulting to 'cdn'

Valid values are 'cdn', 'local', and 'disabled.

  • 'cdn', the default, will use a URL for the Workbox runtime libraries hosted on a highly-available Google Cloud Storage instance.
  • 'local' will copy all of the Workbox runtime libraries into a versioned directory alongside your generated service worker, and configure the service worker to use those local copies. This option is provided for developers who would prefer to host everything themselves and not rely on the Google Cloud Storage CDN.
  • 'disabled' will opt-out automatic behavior. It's up to you to host a local copy of the Workbox libraries at your preferred URL, and to pass in the correct path to workbox-sw.js via the importScripts configuration option.
  • Note: In webpack, passing in a string corresponding to the webpack chunk name containing a custom Workbox runtime library bundle is also supported.

Example:

importWorkboxFrom: 'local'

skipWaiting

Optional Boolean, defaulting to false

Whether or not the service worker should skip over the waiting lifecycle stage. Normally this is used with `clientsClaim: true`.

Example:

skipWaiting: true

clientsClaim

Optional Boolean, defaulting to false

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

Example:

clientsClaim: true

runtimeCaching

Optional Array of Object, defaulting to []

Passing in an array of objects containing urlPatterns, handlers, and potentially options 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 accommodated in runtimeCaching.

The handler values are strings, corresponding to names of the strategies supported by workbox.strategies.

The options properties can be used to configure instances of the cache expiration, cacheable response, and broadcast cache update plugins to apply to a given route.

Example:

runtimeCaching: [{
    // Match any same-origin request that contains 'api'.
    urlPattern: /api/,
    // Apply a network-first strategy.
    handler: 'networkFirst',
    options: {
      // Fall back to the cache after 10 seconds.
      networkTimeoutSeconds: 10,
      // Use a custom cache name for this route.
      cacheName: 'my-api-cache',
      // Configure custom cache expiration.
      expiration: {
        maxEntries: 5,
        maxAgeSeconds: 60,
      },
      // Configure background sync.
      backgroundSync: {
        name: 'my-queue-name',
        options: {
          maxRetentionTime: 60 * 60,
        },
      },
      // Configure which responses are considered cacheable.
      cacheableResponse: {
        statuses: [0, 200],
        headers: {'x-test': 'true'},
      },
      // Configure the broadcast cache update plugin.
      broadcastUpdate: {
        channelName: 'my-update-channel',
      },
      // Add in any additional plugin logic you need.
      plugins: [
        {cacheDidUpdate: () => /* custom plugin code */}
      ],
      // matchOptions and fetchOptions are used to configure the handler.
      fetchOptions: {
        mode: 'no-cors',
      },
      matchOptions: {
        ignoreSearch: true,
      },
    },
  }, {
    // To match cross-origin requests, use a RegExp that matches
    // the start of the origin:
    urlPattern: new RegExp('^https://cors\.example\.com/'),
    handler: 'staleWhileRevalidate',
    options: {
      cacheableResponse: {
        statuses: [0, 200]
      }
    }
  }]

navigateFallback

Optional String, defaulting to undefined

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 use common App Shell HTML.

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

Example:

navigateFallback: '/app-shell'

navigateFallbackBlacklist

Optional Array of RegExp, defaulting to []

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 navigateFallbackBlacklist and navigateFallbackWhitelist are configured, the blacklist takes precedent.

Example:

// Exempt all URLs that start with /_ or contain admin anywhere:
navigateFallbackBlacklist: [/^\/_/, /admin/]

navigateFallbackWhitelist

Optional Array of RegExp, defaulting to []

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 navigateFallbackBlacklist and navigateFallbackWhitelist are configured, the blacklist takes precedent.

Example:

// Include URLs that start with /pages:
navigateFallbackWhitelist: [/^\/pages/]

importScripts

Required Array of String

An required list of JavaScript files that should be passed to importScripts() inside the generated service worker file.

If one of the imported files sets the self.__precacheManifest variable to an array of ManifestEntrys, those entries will be automatically precached in the generated service worker.

This is also 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.

Example:

importScripts: ['push-notifications.abcd1234.js']

ignoreUrlParametersMatching

Optional Array of RegExp, defaulting to [/^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.

Example:

// This will ignore all parameters:
ignoreUrlParametersMatching: [/./]

directoryIndex

Optional String, defaulting to index.html

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 configured to whatever your web server is using, if anything, for its directory index.

Example:

directoryIndex: 'index.html'

cacheId

Optional String, defaulting to null

An optional ID to be prepended to cache names used by Workbox.

This is primarily useful for local development where multiple sites may be served from the same http://localhost:port origin.

Example:

cacheId: 'my-app'

offlineGoogleAnalytics

Optional Boolean, defaulting to false

Controls whether or not to include support for offline Google Analytics.

When true, workbox.googleAnalytics.initialize() will be added to your new service worker file.

Example:

offlineGoogleAnalytics: true

globDirectory

Optional String, defaulting to undefined

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

If you do set this, make sure to also configure globPatterns.

Example:

// Treat all patterns as relative to the current directory:
globDirectory: '.'

globFollow

Optional Boolean, defaulting to 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.

Example:

globFollow: false

globIgnores

Optional Array of String, defaulting to ['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.

Example:

globIgnores: ['**/ignored.html']

globPatterns

Optional Array of String, defaulting to either ['**/*.{js,css,html}'] (for workbox-build and workbox-cli) or [] (for workbox-webpack-plugin)

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

For more information, see the glob primer.

Note: Setting globPatterns is often unnecessary when using the workbox-webpack-plugin, which will automatically precache files that are part of the webpack build pipeline by default. When using the webpack plugin, only set it when you need to cache non-webpack assets.

Example:

globPatterns: ['dist/*.{js,png,html,css}']

globStrict

Optional Boolean, defaulting to 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.

Example:

globStrict: false

templatedUrls

Optional Object with String or Array of String values, defaulting to null

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.

Example:

templatedUrls: {
  '/app-shell': [
    'dev/templates/app-shell.hbs',
    'dev/**/*.css',
    ],
  '/other-page': 'my-version-info',
}

maximumFileSizeToCacheInBytes

Optional Number, defaulting to 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 accidentally matched one of your patterns.

Example:

// Increase the limit to 4mb:
maximumFileSizeToCacheInBytes: 4 * 1024 * 1024

dontCacheBustUrlsMatching

Optional RegExp, defaulting to null

Assets that match this regex 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 those values, as it will reduce the amount of bandwidth consumed when precaching.

Example:

dontCacheBustUrlsMatching: /\.\w{8}\./

modifyUrlPrefix

Optional Object with String values, defaulting to null

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.

Example:

modifyUrlPrefix: {
  // Remove a '/dist' prefix from the URLs:
  '/dist': ''
}

manifestTransforms

Optional Array of ManifestTransform, defaulting to null

One or more ManifestTransform functions, which will be applied sequentially against the generated manifest.

If modifyUrlPrefix or dontCacheBustUrlsMatching are also specified, their corresponding transformations will be applied first.

Example:

manifestTransforms: [
  // Basic transformation to remove a certain URL:
  (originalManifest) => {
    const manifest = originalManifest.filter(
      (entry) => entry.url !== 'ignored.html');
    // Optionally, set warning messages.
    const warnings = []; 
    return {manifest, warnings};
  }
]

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 getManifest mode within a node-based build script like so:

// Inside of build.js:
const {getManifest} = require('workbox-build');

getManifest({
  // Configuration options...
}).then(({manifestEntries, count, size}) => {
  // Do something with the manifestEntries, and potentially log count and size.
});

The supported configuration options are:

globDirectory

Optional String, defaulting to undefined

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

If you do set this, make sure to also configure globPatterns.

Example:

// Treat all patterns as relative to the current directory:
globDirectory: '.'

globDirectory

Optional String, defaulting to undefined

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

If you do set this, make sure to also configure globPatterns.

Example:

// Treat all patterns as relative to the current directory:
globDirectory: '.'

globFollow

Optional Boolean, defaulting to 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.

Example:

globFollow: false

globIgnores

Optional Array of String, defaulting to ['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.

Example:

globIgnores: ['**/ignored.html']

globPatterns

Optional Array of String, defaulting to either ['**/*.{js,css,html}'] (for workbox-build and workbox-cli) or [] (for workbox-webpack-plugin)

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

For more information, see the glob primer.

Note: Setting globPatterns is often unnecessary when using the workbox-webpack-plugin, which will automatically precache files that are part of the webpack build pipeline by default. When using the webpack plugin, only set it when you need to cache non-webpack assets.

Example:

globPatterns: ['dist/*.{js,png,html,css}']

globStrict

Optional Boolean, defaulting to 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.

Example:

globStrict: false

templatedUrls

Optional Object with String or Array of String values, defaulting to null

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.

Example:

templatedUrls: {
  '/app-shell': [
    'dev/templates/app-shell.hbs',
    'dev/**/*.css',
    ],
  '/other-page': 'my-version-info',
}

maximumFileSizeToCacheInBytes

Optional Number, defaulting to 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 accidentally matched one of your patterns.

Example:

// Increase the limit to 4mb:
maximumFileSizeToCacheInBytes: 4 * 1024 * 1024

dontCacheBustUrlsMatching

Optional RegExp, defaulting to null

Assets that match this regex 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 those values, as it will reduce the amount of bandwidth consumed when precaching.

Example:

dontCacheBustUrlsMatching: /\.\w{8}\./

modifyUrlPrefix

Optional Object with String values, defaulting to null

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.

Example:

modifyUrlPrefix: {
  // Remove a '/dist' prefix from the URLs:
  '/dist': ''
}

manifestTransforms

Optional Array of ManifestTransform, defaulting to null

One or more ManifestTransform functions, which will be applied sequentially against the generated manifest.

If modifyUrlPrefix or dontCacheBustUrlsMatching are also specified, their corresponding transformations will be applied first.

Example:

manifestTransforms: [
  // Basic transformation to remove a certain URL:
  (originalManifest) => {
    const manifest = originalManifest.filter(
      (entry) => entry.url !== 'ignored.html');
    // Optionally, set warning messages.
    const warnings = []; 
    return {manifest, warnings};
  }
]