如何使用 workbox-build generateSW 为缓存添加过期时间?

How to add expiration time to caches with workbox-build generateSW?

我使用 workbox generateSW 方法生成服务工作者,这是我使用的配置:

const workbox = require("workbox-build");

workbox.generateSW({
  globDirectory: "./",
  globIgnores: ["node_modules/**", "**/generator.js", "**/sw.js"],
  globPatterns: ["**/*.{css,js}"],
  swDest: "./sw.js",
  sourcemap: false,
  cleanupOutdatedCaches: true,
  clientsClaim: true,
  runtimeCaching: [
    {
      urlPattern: /\.(?:html|htm|xml)$/,
      handler: "StaleWhileRevalidate",
      options: {
        cacheName: "runtimecaching name",
        expiration: {
          maxAgeSeconds: 1,
        },
      },
    },
  ],
});

我在文档中找不到删除旧缓存的过期时间,所以我如何在一段时间后使用 workbox-build generateSW 清理缓存?

maxAgeSeconds 并不是要在一段时间后自动清理旧条目。来自 documentation:

The plugin will check and remove entries after each request or cache update.

One thing to note:

  • Because it’s slow to open IndexedDB, expiration won’t occur until after the request is used. This means that an expired request may be used once, but will be expired after that.
  • To alleviate this, the plugin will check the "Date" header of the cached response, if one exists and the date can be parsed, it’ll expire based on this as it doesn’t require an IndexedDB lookup.

所以maxAgeSeconds是控制缓存请求过时时间的选项,旧条目删除由触发请求。

要在任何请求后检查和删除旧条目,请使用 maxEntries option:

After a cached response is used or a new request is added to the cache, the plugin will look at the configured cache and ensure that the number of cached entries doesn’t exceed the limit. If it does, the oldest entries will be removed.

如果您仍然需要在任何请求后根据时间而不是条目数进行清理,则需要根据 ExpirationPlugin 创建自己的插件并更好地使用注入清单模式。