workbox-build

    Summary

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

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

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

    GenerateSWOptions

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

    InjectManifestOptions

    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

    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

    StrategyName

    Enum

    "CacheFirst"

    "CacheOnly"

    "NetworkFirst"

    "NetworkOnly"

    "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), 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.

    • 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 the swSrc input file. Only valid if compileSrc is true.

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

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

    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

    Returns

    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

    Returns

    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

    Returns

    This site uses cookies to deliver and enhance the quality of its services and to analyze traffic. If you agree, cookies are also used to serve advertising and to personalize the content and advertisements that you see. Learn more about our use of cookies.