Workbox webpack Plugin

What's the Workbox webpack Plugin?

This is a plugin for webpack which generates a list of URLs to precache (known as a "precache manifest") based on the assets in a webpack compilation.

Guidance on using the plugin within the context of a larger webpack build can be found in the "Progressive Web Application" section of the webpack documentation.

Considerations

There are a few decisions to make which will determine the right configuration for your use case.

Should the plugin create your service worker file?

If you leave out the swSrc configuration option, the plugin will create a service worker file for you and automatically add it to the webpack asset pipeline. This is referred to as generateSW mode.

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.

If you set swSrc to the path of an existing service worker file (which does not have to be otherwise configured as a webpack asset) then the plugin will generate a list of URLs to precache and add a reference to that precache manifest, along with a reference to the Workbox runtime code, to your file. It will otherwise leave the file as-is. This is referred to as injectManifest mode.

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.

Do you need to cache additional, non-webpack assets?

By default, the plugin will generate a precache manifest that contains URLs for all of the assets that come from the current webpack compilation. Any assets that webpack doesn't "know" about will not be picked up.

If you need to precache additional assets that are managed outside of webpack, then you can use the globDirectory and globPatterns options to specify how to find those additional assets.

If you decide to use globDirectory and globPatterns, the following applies:

  • The glob pattern matching will be performed against the local file system, and the directory that globDirectory is set to must exist at the time the plugin runs. This might run afoul of webpack-dev-server configurations, where an in-memory file system is used.
  • The options that work with glob-based precache manifests, like manifestTranforms and modifyUrlPrefix, can also be used, but they'll apply only to the entries that are matched via glob patterns, and not to any assets that are picked up via the webpack compilation.

Configuration

Once you've determined the answers to those considerations, you can pass the appropriate configuration as properties of an Object to the plugin's constructor. For example:

// Inside of webpack.config.js:
const WorkboxPlugin = require('workbox-webpack-plugin');

module.exports = {
  // Other webpack config...
  plugins: [
    // Other plugins...
    WorkboxPlugin({option: 'value'})
  ]
};
Supported Options

chunks

Optional Array of String, defaulting to []

By default, Workbox will precache all assets generated by the webpack compilation, regardless of which chunk the asset is part of.

If you would like to override this behavior via a whitelist, specify one or more chunk names. Only assets belonging to those chunks will be precached; any assets belonging to another chunk or without a chunk association will be skipped.

Example:

// *Only* include assets that belong to these chunks:
chunks: ['chunk-name-1', 'chunk-name-2']

excludeChunks

Optional Array of String, defaulting to []

By default, Workbox will precache all assets generated by the webpack compilation, regardless of which chunk the asset is part of.

If you would like to override this behavior via a blacklist, specify one or more chunk names. Any assets belonging to those chunks will be skipped.

Example:

// Exclude assets that belong to these chunks:
chunks: ['chunk-name-1', 'chunk-name-2']

filename

Optional String, defaulting to 'sw.js'

The name to use for the generated service worker file. The file's path depends on the output.path directory in the overall webpack configuration.

Example:

filename: 'service-worker.js'

globDirectory

Optional String, defaulting to undefined

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

This only needs to be set if you want to precache additional local files that are not created by the webpack build process.

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 []

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

For more information, see the glob primer.

This only needs to be set if you want to precache additional local files that are not created by the webpack build process.

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

Example:

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

importScripts

Optional Array of String

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

By default, the generated service worker file will automatically import both the precache manifest and the Workbox runtime code. You can set this option if you need to import additional scripts, like code to add a push event listener.

Example:

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

manifestFilename

Optional String, defaulting to 'file-manifest[hash].js'

The name to use for the generated JavaScript file containing ManifestEntrys corresponding to the precached assets. The code in the file assigns the entries to the self.__precacheManifest variable.

It is strongly recommended to use a value that contains a webpack-controlled [hash], to ensure that changes to the contents result in an updated filename.

Example:

manifestFilename: 'my-manifest-[hash].js'

swSrc

Optional String, defaulting to undefined

If swSrc is left undefined, the plugin will generate a brand-new service worker file as part of each compilation, configured based on the options provided.

If swSrc is provided, the plugin assumes it refers to an existing service worker file. The code in this file will be included as-is, with one addition: a call to importScripts() will be prepended to the existing code, automatically configured to import the generated manifestFilename file, as well as the necessary Workbox runtime library code.

When providing swSrc, your service worker code can reference the self.__precacheManifest variable to obtain a list of ManifestEntrys obtained as part of the compilation: workbox.precaching.precacheAndRoute(self.__precacheManifest)

Example:

swSrc: path.join('dev', 'sw.js')

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'

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

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'

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: [/./]

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/]

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.

Example:

runtimeCaching: [{
  // Match same-origin requests for URLs ending in .jpg:
  urlPattern: /.jpg$/,
  handler: 'cacheFirst',
  // Any options provided will be used when
  // creating the caching strategy.
  options: {
    cacheName: 'image-cache',
    cacheExpiration: {
      maxEntries: 10
    }
  }
}, {
  // 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]
    }
  }
}]

skipWaiting

Optional Boolean, defaulting to false

Whether or not the service worker should skip over the waiting lifecycle stage.

Example:

skipWaiting: true

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}\./

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 ['**/*.{js,css,html}']

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

For more information, see the glob primer.

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

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:
  (entries) => entries.filter((entry) => entry.url !== 'ignored.html')
]

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

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': ''
}

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',
}