问题
I'm trying to set up a simple Service Worker for a small static site.
precache a couple of pages. cache *.html files for just 5 mins cache all other files for 30 days handle 404 and offline status with an offline page.
I get service worker console error sw.js:59 Uncaught TypeError: workbox.expiration.CacheableResponsePlugin is not a constructor
this is at the line new workbox.expiration.CacheableResponsePlugin({
Any suggestions on how to fix this would be appreciated.
/**
* Welcome to your Workbox-powered service worker!
*
* You'll need to register this file in your web app and you should
* disable HTTP caching for this file too.
*
*
* The rest of the code is auto-generated. Please don't update this file
* directly; instead, make changes to your Workbox build configuration
* and re-run your build process.
*
*/
importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.0.0/workbox-sw.js')
if (workbox) {
console.log('Yay! Workbox is loaded');
/**
* The workboxSW.precacheAndRoute() method efficiently caches and responds to
* requests for URLs in the manifest.
*
*/
/* https://developers.google.com/web/tools/workbox/modules/workbox-sw -namespace */
/* https://developers.google.com/web/tools/workbox/guides/precache-files */
workbox.precaching.precacheAndRoute(
[
{ url: "404.html", revision: "dc3feaa1058d8c1efcea96fefc3153ed" },
{ url: "offline.html", revision: "e0683df2f740244dd3788ae2347e2bb4" }
]
);
workbox.routing.registerRoute(
/\.(?:png|gif|jpg|svg|css|js|json)$/,
new workbox.strategies.CacheFirst({
cacheName: 'nonhtml-cache',
plugins: [
new workbox.expiration.ExpirationPlugin({
maxEntries: 50,
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
})
]
})
)
workbox.routing.registerRoute(
/\.(?:html)$/,
new workbox.strategies.NetworkFirst({
cacheName: 'html-cache',
plugins: [
new workbox.expiration.CacheableResponsePlugin({
statuses: [0, 200],
}),
new workbox.expiration.ExpirationPlugin({
maxEntries: 50,
maxAgeSeconds: 5 * 60,
})
]
})
)
//changes replace /404 with 404, replace php$ with php
workbox.routing.registerRoute(/\.html/, args => {
return articleHandler.handle(args).then(response => {
if (!response) {
return caches.match('offline.html');
} else if (response.status === 404) {
return caches.match('404.html');
}
return response;
});
});
} else {
console.log('Boo! Workbox did not load');
}
回答1:
I was migrating from workbox
v4 to v5 and having the same problem.
In your code,
new workbox.expiration.CacheableResponsePlugin
should be
new workbox.cacheableResponse.CacheableResponsePlugin
回答2:
Example:
workbox.routing.registerRoute(new RegExp('https://assets.abcd.com/.*\.*'),
new workbox.strategies.CacheFirst({
cacheName: 'assets',
plugins: [
new workbox.cacheableResponse.Plugin({
statuses: [0, 200, 206] // 206 Partial Code.
}),
new workbox.rangeRequests.Plugin()
]}))
来源:https://stackoverflow.com/questions/60310455/workbox-5-syntax-error-uncaught-typeerror-workbox-expiration-cacheablerespons