首页 > 解决方案 > Create React App v4 生成的 PWA 中的 API 缓存

问题描述

是使用的模板cra-template-pwa-typescript。如何缓存外部 API 和图像?

标签: reactjscreate-react-appprogressive-web-apps

解决方案


c-r-av4 使用一个模型,在该模型中,您可以完全控制由 Workbox 提供支持的 Service Worker 文件。

Workbox 文档中有关缓存的一般指南应该会有所帮助:https ://developers.google.com/web/tools/workbox/guides/handle-third-party-requests

举一个具体的例子,假设您想使用 stale-while-revalidate 策略缓存所有跨域图像。您可以通过将此路由添加到您的服务工作人员文件来做到这一点:

registerRoute(
  ({request, url}) => url.origin !== self.location.origin &&
                      request.destination === 'image',

  new StaleWhileRevalidate({
    cacheName: 'cross-origin-images',
    plugins: [
      // Ensure that once this runtime cache reaches a maximum size the
      // least-recently used images are removed.
      new ExpirationPlugin({ maxEntries: 50 }),
    ],
  })
);

推荐阅读