workbox-webpack-plugin

Workbox provides two webpack plugins: one that generates a complete service worker for you and one that generates a list of assets to precache that is injected into a service worker file.

The plugins are implemented as two classes in the workbox-webpack-plugin module, named GenerateSW and InjectManifest. The answers to the following questions can help you choose the right plugin and configuration to use.

Which Plugin to Use

GenerateSW

The GenerateSW plugin will create a service worker file for you and add it to the webpack asset pipeline.

When to use GenerateSW

  • You want to precache files.
  • You have simple runtime caching needs.

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 for custom caching strategies.

InjectManifest

The InjectManifest plugin 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 need to customize routing and strategies.
  • You would like to use your service worker with other platform features (e.g. Web Push).

When NOT to use InjectManifest

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

GenerateSW Plugin

You can add the GenerateSW plugin to your webpack config like so:

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

module.exports = {
  // Other webpack config...
  plugins: [
    // Other plugins...
    new GenerateSW({
      // These are some common options, and not all are required.
      // Consult the docs for more info.
      exclude: [/.../, '...'],
      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: ...,
    }),
  ],
};

This will generate a service worker with precaching setup for all of the webpack assets 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 Plugin

You can add the InjectManifest plugin to your webpack config like so:

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

module.exports = {
  // Other webpack config...
  plugins: [
    // Other plugins...
    new InjectManifest({
      // These are some common options, and not all are required.
      // Consult the docs for more info.
      exclude: [/.../, '...'],
      maximumFileSizeToCacheInBytes: ...,
      swSrc: '...',
    }),
  ],
};

This will create a precache manifest based on the webpack assets picked up by your configuration and inject it into your bundled and compiled service worker file.

A full set of configuration options can be found in the reference documentation.

Extra Info

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

Types

GenerateSW

This class supports creating a new, ready-to-use service worker file as part of the webpack compilation process.

Use an instance of GenerateSW in the plugins array of a webpack config.

// The following lists some common options; see the rest of the documentation
// for the full set of options and defaults.
new GenerateSW({
  exclude: [/.../, '...'],
  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: ...,
});

Properties

GenerateSWConfig

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.

  • 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.

  • chunks

    string[] optional

    One or more chunk names whose corresponding output files should be included in the precache manifest.

  • 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

  • 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.

  • 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.

  • 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.

  • 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().

  • 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.

  • 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.

  • manifestEntries

    ManifestEntry[] optional

  • manifestTransforms

    ManifestTransform[] optional

    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.

  • 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 current webpack compilation will be used.

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

  • offlineGoogleAnalytics

    boolean | GoogleAnalyticsInitializeOptions optional

    Default value is: false

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

  • runtimeCaching

    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. 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.

  • swDest

    string optional

    Default value is: "service-worker.js"

    The asset name of the service worker file created by this plugin.

InjectManifest

This class supports compiling a service worker file provided via swSrc, and injecting into that service worker a list of URLs and revision information for precaching based on the webpack asset pipeline.

Use an instance of InjectManifest in the plugins array of a webpack config.

In addition to injecting the manifest, this plugin will perform a compilation of the swSrc file, using the options from the main webpack configuration.

// The following lists some common options; see the rest of the documentation
// for the full set of options and defaults.
new InjectManifest({
  exclude: [/.../, '...'],
  maximumFileSizeToCacheInBytes: ...,
  swSrc: '...',
});

Properties

  • constructor

    void

    Creates an instance of InjectManifest.

    The constructor function looks like:

    (config: WebpackInjectManifestOptions) => {...}

    • config

      WebpackInjectManifestOptions

  • config

    WebpackInjectManifestOptions

Properties

default

Type

object

Properties

  • GenerateSW

    query

  • InjectManifest

    query