1

我正在使用工作箱服务工作者通过为每个创建自定义缓存来缓存图像和 API 响应。虽然我可以看到路由匹配,但我看不到存储在缓存中的响应,然后由于缓存未命中,服务工作者正在从网络请求每个资源。

我已经为 service worker 使用了 workbox-webpack-plugin,并在其他文件中编写了自定义路由和缓存策略,然后将其传递给插件配置。

同样,我的 css 和 js 文件存储和服务都很好。

我尝试过使用不同的缓存策略,以及没有 webpack 插件的解决方法,但它们似乎都不起作用

//Cache JS files
    workbox.routing.registerRoute(
        new RegExp('.*\.js'),
        workbox.strategies.cacheFirst()
    );

//Cache API response
workbox.routing.registerRoute(
     new RegExp('\/api\/(xyz|abc|def)'),
         workbox.strategies.staleWhileRevalidate({
         cacheName: 'apiCache',
             plugins : [
                new workbox.expiration.Plugin({
                    maxEntries: 100,
                    maxAgeSeconds: 30 * 60 // 30 Minutes
                 })
            ]
    })
);

//cache images
workbox.routing.registerRoute(
    new RegExp('(png|gif|jpg|jpeg|svg)'),
    workbox.strategies.cacheFirst({
        cacheName: 'images',
        plugins: [
            new workbox.expiration.Plugin({
                maxEntries: 60,
                maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
            })
       ]
  })
);

这是 webpack 配置:

new workboxPlugin.InjectManifest({
    swSrc: 'customWorkbox.js',
    swDest: 'sw.js'
})
4

1 回答 1

2

根据工作箱文档,外部 api 的正则表达式需要从一开始就匹配:

Instead of matching against any part of the URL, the regular expression must match from the beginning of the URL in order to trigger a route when there's a cross-origin request.

于 2019-01-10T00:20:58.927 回答