You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React Vite PWA应用中预缓存API请求?

解决Vite React PWA预缓存API请求的问题

为什么直接用precacheAndRoute无效

precacheAndRoute是Workbox专门用来预缓存编译生成的静态资源(如JS、CSS、图片)的方法,这类资源带有哈希文件名,Workbox会通过预缓存清单统一管理。而API请求属于动态内容,不在静态资源清单范围内,直接传入路径无法触发预缓存。

解决方案一:在自定义Service Worker中使用warmupCache

这种方式会在Service Worker安装阶段主动发起API请求并缓存,适合需要确保API数据提前离线可用的场景。

1. 修改VitePWA配置为injectManifest模式

切换到该模式可自定义Service Worker逻辑,同时保留Workbox的静态资源预缓存能力:

const pwaOptions: Partial<VitePWAOptions> = {
  mode: "development",
  base: "/",
  includeAssets: ["vite.svg", "favicon.png"],
  manifest: {
    name: "PWA Router",
    short_name: "PWA Router",
    theme_color: "#ffffff",
    icons: [
      {
        src: "favicon.png", 
        sizes: "200x200",
        type: "image/png",
      },
    ],
  },
  // 切换到injectManifest模式
  strategies: 'injectManifest',
  srcDir: 'src',
  filename: 'sw.ts',
  workbox: {
    runtimeCaching: [
      {
        urlPattern: ({ url: { pathname } }) => pathname.startsWith("/api"),
        handler: "CacheFirst" as const,
        options: {
          cacheName: "api-cache",
          cacheableResponse: {
            statuses: [0, 200],
          },
        },
      },
    ],
  },
  devOptions: {
    enabled: process.env.SW_DEV === "true",
    type: "module",
    navigateFallback: "index.html",
  },
};

2. 编写自定义Service Worker文件(src/sw.ts)

import { precacheAndRoute, warmupCache } from 'workbox-precaching';

// 处理静态资源的预缓存(清单由VitePWA自动注入)
precacheAndRoute(self.__WB_MANIFEST);

// 定义需要预缓存的API列表
const apiUrls = ['/api/my-ep'];

// 执行API预缓存的方法
async function precacheApis() {
  await warmupCache(apiUrls, {
    cacheName: 'api-cache', // 和runtimeCaching的缓存名称保持一致
  });
}

// 在Service Worker安装完成后触发预缓存
self.addEventListener('install', (event) => {
  event.waitUntil(precacheApis());
});

解决方案二:应用初始化时主动触发API缓存

这种方式无需修改Service Worker模式,实现简单,在用户打开应用后主动请求API并触发缓存:

在根组件(如App.tsx)中添加初始化逻辑:

import { useEffect } from 'react';

function App() {
  useEffect(() => {
    // 应用加载后主动请求API,触发runtimeCaching缓存
    fetch('/api/my-ep')
      .then(res => res.json())
      .catch(err => console.error('API预缓存失败:', err));
  }, []);

  return <div>你的应用内容</div>;
}

export default App;

注意事项

  • 开发环境下需确保SW_DEV=true,且devOptions.enabled为true才能测试离线功能。
  • 确保API响应允许缓存:要么响应头Cache-Control配置合理,要么在cacheableResponse.statuses中包含对应的状态码(如200)。
  • 若API需要认证,预缓存时需携带正确的认证信息,注意不要在Service Worker中存储敏感数据。

内容的提问来源于stack exchange,提问作者rudzky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 04:20:55