This repository was archived by the owner on Feb 16, 2020. It is now read-only.
Update dependency workbox-webpack-plugin to v5 #28
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR contains the following updates:
4.3.1->5.0.0Release Notes
googlechrome/workbox
v5.0.0Compare Source
Overview of Workbox v5
We're happy to announce the release of Workbox version 5! This release introduces a lot of new features, as well as some breaking changes.
If you're already using Workbox, the best place to get up to speed is the guide to migrating from v4 to v5.
One example migration, with commentary, can be found in this GitHub commit.
🎉 What's New?
A shift towards local Workbox bundles & away from the CDN
While our immediate plan is to continue publishing copies of the Workbox runtime code to our CDN, in v5, the
generateSWmode of our build tools will create a local bundle of exactly the Workbox runtime methods you end up using in your service worker. Depending on the value ofinlineWorkboxRuntime, this bundle will either be imported from a separate file, or inlined directly in your top-level service worker.Under the hood, we use Rollup to create this optimized bundle, optionally minifying it and generating sourcemaps, depending on the configuration.
See #2064 for more details.
If you're using the
workbox-webpack-plugin'sInjectManifestmode, the service worker file you specify viaswSrcwill end up being run through awebpackcompilation process, optionally applying any compilation plugins configured via thewebpackPluginsparameter. This should simplify the development flow described in the Using Bundlers (webpack/Rollup) with Workbox guide.See #1513 for more details.
You can continue using
importScripts('http://storage.googleapis.com/workbox-cdn/releases/5.0.0/workbox-sw.js')and relying onworkbox-swto dynamically pull in the Workbox runtime code that you need in v5, but we expect that using a custom bundle will lead to smaller runtime payloads (as well as work around issues with asynchronous imports), and we encourage developers to consider switching off of the CDN.Changes to the webpack precache manifest
Before v5,
workbox-webpack-pluginwould generate a list of entries to precache based on two distinct sources: the set of assets in awebpackcompilation, along with an optional additional set of files matched viaglobpatterns. Mostwebpackdevelopers did not use theglob-related options (since thewebpackcompilation would normally include all the assets that they cared about), but at the same time, some helpful configuration options for manipulating or post-processing the precache manifest only applied to entries created via thoseglobpatterns.In v5, the
glob-related configuration options are no longer supported. Thewebpackasset pipeline is the source of all the automatically created manifest entries. (Developers who have files that exist outside of thewebpackasset pipeline are encouraged to use, e.g.,copy-webpack-pluginto get those files into thewebpackcompilation.)Beyond that, options for post-processing the precache manifest can now be used to manipulate entries that originate from the
webpackasset pipeline.manifestTransforms, in particular, can be used to make arbitrary changes to any aspect of the precache manifest, including adding entries, deleting them, and changing theirrevisionorurlfields as needed. The currentwebpackcompilation will be passed in to the callback function in case you need information from there to determine how to manipulate entries.Here's an example of using
manifestTransformsto perform extensive post-processing of a precache manifest:Helpers that implement common manifest transformations, like
maximumFileSizeToCacheInBytes,dontCacheBustURLsMatchingandmodifyURLPrefix, are also supported forwebpackassets.See #1591 and #1854.
Additionally, in v5, the precache manifest is inlined into the top-level service worker file, and not stored in a separate, external JavaScript file.
Simplified injectManifest placeholder replacement
Prior to v5, manifest injection worked by using a regular expression to find the correct location in the source service worker file to replace with the array of manifest entries. This could be brittle, and it was hard to customize, since the replacement step assumed you were using a
RegExpthat had capture groups.This is simplified in v5, and using the
injectManifestmode just checks for a placeholder variable and performs the equivalent of string replacement to inject the full manifest in its place. This variable isself.__WB_MANIFESTby default.Your
swSrcfile in v4 might have looked likeprecacheAndRoute([]);In v5, you should change this to
precacheAndRoute(self.__WB_MANIFEST);self.__WB_MANIFESTwas chosen as the default replacement because self should always be defined in the service worker global scope, and it is unlikely to conflict with any user-created variables. If you need a different replacement, it can be configured via theinjectionPointoption.See #2059 for more details.
TypeScript support
All browser-based Workbox packages are now written in TypeScript and type definitions have been published to npm. TypeScript users (as well as users with TypeScript-aware code editors) can now get type checking for all browser-exposed Workbox APIs. (There are no TypeScript definitions for the various Workbox build tools at this time.)
To get type definitions for any Workbox APIs, you can import the package as described in our guide on Using Bundlers (webpack/Rollup) with Workbox. For example:
Note, we've historically published our Workbox source modules with the
.mjsextension as a way to disambiguate them from classic scripts and the examples in our documentation that reference file paths always use.mjs.However, since TypeScript does not currently support importing .mjs files we publish both
.jsand.mjsfiles to npm. TypeScript users wanting to import an individual module should be able to reference it by omitting the extension (which will then default to the.jsfile).If you encounter any problems with the type definitions or importing the source files via TypeScript, please let us know by opening an issue on GitHub.
additionalManifestEntries option in build tools
All of the build tools (
generateSWandinjectManifestmodes inworkbox-build,workbox-cli, andworkbox-webpack-plugin) now support a new option:additionalManifestEntries. [#2124] It can be set to a list of additional precache manifest entries that go beyond what would normally be included as part of your build (such as CDN URLs), and is a shortcut to something that is otherwise possible via themanifestTransformsoption.Before using this feature, please keep in mind that
workbox-precachingrequires one of two things from each entry in order to keep precached content up to date:revisionfield alongside an unversioned URL, providing versioning information that is updated each time new contents are deployed to that URL. E.g.{url: https://example.com/index.js, revision: hashOfIndexJsContents}The precache manifest entries generated by Workbox's built tools can automatically add in
revisionfields for you, but when usingadditionalManifestEntries, it's up to you to ensure that you only add in versioned URLs, or that you include arevisionfield that will always change whenever the corresponding URL changes.To ensure that developers are aware of this, passing in string values in the
additionalManifestEntrieswill result in a non-fatal warning message, asking you to confirm that your URLs are versioned. To avoid this message, pass in an object with arevision: nullproperty instead of a string, like{url: http://example.com/v1.0.0/index.js, revision: null}.importScriptsViaChunks in workbox-webpack-plugin's GenerateSW mode
A new option,
importScriptsViaChunks, is supported in theGenerateSWmode of the webpack plugin. [#2131] Passing in one or more chunk names will cause the corresponding script files to be included in the generated service worker, viaimportScripts().Because of the way script caching works with
importScripts(), developers should ensure that their chunks' filenames include a hash, so that changes to a chunk's contents will result in new filename.Support for subresource integrity metadata in precaching requests
Precache manifest entries can now include an optional property,
integrity. If provided, that value will be treated as the integrity metadata for in thefetch()request used to populate the precache. [#2141]There is currently no option in the Workbox build tools for generating this metadata; it's left as an exercise to developers to use the
manifestTransformsoption to post-process the generated precache manifests and add inintegrityproperties, with appropriate values, to the entries that need that extra validation.update(), to force a service worker update check
A new
update()method has been added toworkbox-window. When called, it will invoke theupdate()method on the underlyingServiceWorkerRegistrationobject. [#2136]Calling this method is optional, as browsers will automatically check for service worker updates whenever there's a navigation request to a new page, along with a few other scenarios. However, as described in this guide, manually requesting a service worker update can be useful for long-lived, single-page apps.
Navigation route changes
Two options that were previously supported for navigation routes,
blacklistandwhitelisthave been renameddenylistandallowlist.workbox-routingpreviously supported a method,registerNavigationRoute(), that, under the hood, did two things:fetchevent had amode of 'navigate'.This is a common pattern to use when implementing the App Shell architecture.
The second step, generating a response by reading from the cache, falls outside of what we see as the responsibilities of
workbox-routing. Instead, we see it as functionality that should be part ofworkbox-precaching, via a new method,createHandlerBoundToURL(). This new method can work hand-in-hand with the existingNavigationRouteclass inworkbox-routingto accomplish the same logic.If you're using the
navigateFallbackoption in one of the build tool's "generate SW" mode, then the switchover will happen automatically. If you previously configured either thenavigateFallbackBlacklistornavigateFallbackWhitelistoptions, please change those tonavigateFallbackDenylistornavigateFallbackAllowlist, respectively.If you're using "inject manifest" mode or just writing the service worker yourself, and your Workbox v4 service worker calls
registerNavigationRoute()directly, then you'll have to make a change to your code to get the equivalent behavior.You no longer need to call
getCacheKeyForURL(), ascreateHandlerBoundToURL()will take care of that for you.workbox-broadcast-update
A
generatePayload()configuration option has been added to theBroadcastCacheUpdateandBroadcastUpdatePluginclasses that allows developers to customize the message that gets sent to the window when a cached response has been updated.The
generatePayload()function is called with the same arguments as thecacheDidUpdate()plugin callback, and its return value will be used as the message payload. Here's an example that adds theLast-Modifiedheader value of the updated response to the payload:New copyResponse method
A
copyResponse()method has been added that can be used to clone a response and modify itsheaders,status, orstatusText. [#2193]Here's an example that adds a custom header to indicate that a response came from the cache (and not the network):
Changes to the precaching network requests
If
workbox-precachingneeds to bypass the HTTP cache when requesting a URL, it will now setcache: 'reload'on the outgoingRequest, which in turns sets the appropriateCache-Controlheaders. [#2176]Previously, bypassing the HTTP cache was done by adding in a
__WB_REVISION=...URL query parameter to the outgoing network request, meaning that backend web servers would see requests for URLs containing those query parameters. With this change in place, requests for URLs with__WB_REVISION=...should no longer be seen in HTTP server logs.Please note that this change only applies to outgoing HTTP requests used to populate the precache, and does not apply to cache keys. The keys for some entries created by
workbox-precachingstill include the__WB_REVISION=...parameter, and it's still a best practice to callgetCacheKeyForURL()to determine the actual cache key, including the__WB_REVISIONparameter, if you need to access precached entries using the Cache Storage API directly.Control over development logging
A new
__WB_DISABLE_DEV_LOGSglobal has been added. Set it tofalseto disable all logging in development mode. [#2284]New helper methods to read precached responses
Two new methods (
matchPrecache()andcreateHandler()) have been added to make it easier to manually access precached assets. [#2254]All build tools
Any
manifestTransformcallbacks are now treated as beingasync, and each callback will beawait-ed by the build tools. If you supply multiple transforms, they will still be run sequentially, in the same order. [#2195]This should not be a breaking change, as you can continue providing non-
asynccallback functions, and they will still work as before.workbox-build and workbox-cli
As part of a general refactoring of how the options passed to all of our build tools are parsed [#2191], using precaching in the
generateSWmode ofworkbox-buildandworkbox-cliis no longer mandatory. You can now use theruntimeCachingoptions without configuring theglob-related options, and your generated service worker will just contain the corresponding runtime caching routes.If you don't configure the
glob-related options and you don't useruntimeCaching, that will lead to a build error.All Build Tools
A number of
workbox-build,workbox-cli, andworkbox-webpack-pluginconfiguration parameters are no longer supported, following the general outlines of the changes described above. For instance,generateSWwill always create a local Workbox runtime bundle for you, so theimportWorkboxFromoption no longer makes sense. Please consult the relevant tool's documentation for the list of supported options.navigationRouteWhitelisthas been renamednavigationRouteAllowlist, andnavigationRouteBlacklisthas been renamednavigationRouteDenylist. The functionality is otherwise identical.All Plugin classes
All
Pluginclasses have been renamed to be package-specific, e.g.ExpirationPlugin,CacheableResponsePlugin, etc. If you're using one of the Workbox build tools ingenerateSWmode to create your service worker, this change will be handled for you automatically. If you use one of the plugins in a manually created service worker, you'll need to explicitly change instances ofPluginto the correct revised class name. [#2187]workbox-broadcast-update
The
workbox-broadcast-updatepackage no longer usesBroadcastChannel, even in cases when the browser supports it. Instead it usespostMessage()to message window clients. [#2184]This change was made because
postMessage()messages are automatically buffered by the window to handle cases where the service worker sends a message before the code running on the window is ready to receive it.BroadcastChannelhas no such buffering, and thus you're more likely to miss message when using it.If you're currently listening for
BroadcastChannelmessages in your code running on the window, you'll now need to listen formessageevents on theServiceWorkerContainer:Note:
workbox-windowusers should not need to make any changes, as its internal logic has been updated to listen forpostMessage()calls.workbox-build
The
generateSWStringmode has been removed. We expect the impact of this to be minimal, as it was primarily used internally byworkbox-webpack-plugin.The minimum required version of node has been increased to
v8.0.0. This also applies to build tools that useworkbox-build, likeworkbox-cliandworkbox-webpack-plugin.workbox-routing
workbox-strategies
makeRequest()in favor ofhandle(). CallingmakeRequest()is mostly equivalent to callinghandle()on one of theworkbox-strategyclasses. The differences between the two methods were so slight that keeping both around did not make sense. Developers who calledmakeRequest()should be able to switch to usinghandle()without any further change. [#2123]workbox-webpack-plugin
webpackv4 or higher.🐛 What's Fixed?
All build tools
swSrcfile has an associated sourcemap, we now update that to account for the injected manifest. [#2239]workbox-broadcast-update
workbox-precaching
cacheWillUpdate()plugin callback was not beingawait-ed. [#2287]workbox-routing
matchCallbackstring/number return values through tohandlerCallback. [#2134]ReadableStreambug in development mode in Safari. [#2268]workbox-webpack-plugin
workbox-webpack-pluginin the same compilation, assets created by those other instances will now be excluded from each others' precache manifest. [#2182]workbox-window
isUpdateproperty to thecontrollingevent, which was documented but not actually implemented. [#2114]messageevent listener is now added earlier, inside of the constructor rather than theregister()method. [#2211]🙏 Thanks!
A sincere thank you to everyone who tested Workbox v5, and in particular to the following folks who filed bugs and made contributions to the code. (Apologies if we've missed anyone—it's been a long process!)
Code Contributions
Bug Reports
Renovate configuration
📅 Schedule: At any time (no schedule defined).
🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.
♻️ Rebasing: Whenever PR becomes conflicted, or if you tick the rebase/retry checkbox below.
🔕 Ignore: Close this PR and you won't be reminded about this update again.
This PR has been generated by WhiteSource Renovate. View repository job log here.