我正在从Workbox的v3升级到v5。我没有使用捆绑器,因为我的SPA是使用Blazor构建的。我正在使用用纯正的javascript编码的服务工作者,正在使用从Google CDN导入的工作箱javascript文件,并且未使用捆绑器。
如果不使用捆绑程序和模块,有没有一种方法可以“翻译”当前的v5工作箱文档?
例如,使用来自Google CDN的importScripts,编写以下代码的普通javascript方法是什么:
import {registerRoute} from 'workbox-routing';
import {CacheFirst, StaleWhileRevalidate} from 'workbox-strategies';
import {CacheableResponsePlugin} from 'workbox-cacheable-response';
import {ExpirationPlugin} from 'workbox-expiration';
// Cache the Google Fonts stylesheets with a stale-while-revalidate strategy.
registerRoute(
({url}) => url.origin === 'https://fonts.googleapis.com',
new StaleWhileRevalidate({
cacheName: 'google-fonts-stylesheets',
})
);
// Cache the underlying font files with a cache-first strategy for 1 year.
registerRoute(
({url}) => url.origin === 'https://fonts.gstatic.com',
new CacheFirst({
cacheName: 'google-fonts-webfonts',
plugins: [
new CacheableResponsePlugin({
statuses: [0, 200],
}),
new ExpirationPlugin({
maxAgeSeconds: 60 * 60 * 24 * 365,
maxEntries: 30,
}),
],
})
);
我特别难以转换这段旧代码:
workbox.routing.registerRoute(
/\.(?:png|svg|js|css|html|woff|eot|otf|ttf|ico|dll|json|wasm|dat|pdb)$/,
new workbox.strategies.StaleWhileRevalidate({
cacheName: 'dplan-cache',
plugins: [
new workbox.expiration.Plugin({
maxAgeSeconds: 60 * 60 * 24 * 7 //7 days
})
]
})
);
我有例外:
Uncaught TypeError: workbox.expiration.Plugin is not a constructor
我认为https://developers.google.com/web/tools/workbox/guides/using-bundlers#moving_from_importscripts_to_module_imports是在两种导入Workbox方式之间进行转换的最佳指南。
特定于版本的升级指南也将有所帮助;特别是,我认为您遇到的是v4 to v5与plugin classes相关的更改。
使用workbox.expiration.ExpirationPlugin
应该可以。