如何在 Cloudflare Worker 中拦截请求并返回 Vite 生成的 HTML?

解读

这道题表面问“拦截+返回”,实则考察三件事:

  1. 是否理解 Vite 在「生产」与「开发」两种模式下的产物差异;
  2. 是否熟悉 Cloudflare Worker 的运行时限制(无 Node、无文件系统、128 MB 内存、CPU 10 ms);
  3. 能否把「把静态资源搬到 Worker 上」这件事做得既合规又高效。
    国内面试里,这道题常作为「边缘渲染」或「微前端接入」环节的延伸,答得太浅会被追问缓存策略,答得太深又容易踩“把 node_modules 塞进 Worker”这种红线,因此需要给出一条“国内云厂商可落地”的中等复杂度方案。

知识点

  1. Vite 生产构建产物
    • dist/index.html 是入口,内部通过 assets/main-xxx.js 等哈希文件引用资源。
    • 所有资源默认带哈希,适合强缓存一年。
  2. Cloudflare Worker 运行时能力
    • 只能拿到 JS Runtime,无文件系统,但支持 fetch() 与 caches API。
    • 单个脚本压缩后 ≤ 1 MB,上传前需 tree-shaking。
  3. 国内合规加速
    • 域名必须备案;Worker 本身不走备案,但回源域名需备案,否则易被运营商丢包。
    • 建议把静态文件放国内 OSS(阿里云 OSS、腾讯云 COS),Worker 只做「边缘 HTML 直出 + 统一兜底」。
  4. 缓存分层
    • Worker 内部用 cache.put() 把 HTML 缓存在边缘节点,TTL 由 Cache-Control 控制。
    • 静态资源用 OSS 自带 CDN,不要走 Worker,避免额外费用。
  5. 开发阶段调试
    • 用 wrangler dev --local 模拟最小环境,把 dist 目录挂到 http://localhost:8787,验证路由。
    • 注意 vite build --mode staging 可注入 BASE_URL=/__worker_proxy/ 方便本地联调。

答案

步骤一:构建
在项目根目录执行

vite build

得到 dist/index.html 与 assets/* 文件。

步骤二:把静态资源推到国内 OSS

ossutil cp -rf dist/ oss://your-bucket/vite-app/

设置 HTTP 头:

Cache-Control: public, max-age=31536000, immutable

并开启 CDN,回源 HOST 填已备案域名。

步骤三:编写 Worker 脚本

// worker.js
import indexHtml from './dist/index.html'  // 通过 wrangler 的「text import」语法内联

const OSS_BASE = 'https://cdn.your-domain.com/vite-app'

async function handleFetch(event) {
  const { request } = event
  const url = new URL(request.url)

  // 1. 只拦截根路径及客户端路由的伪路径
  if (!/^\/($|article\/|product\/)/.test(url.pathname)) {
    return fetch(request) // 其余请求直接回源
  }

  // 2. 边缘缓存 key
  const cacheKey = new Request(url.toString(), request)
  const cache = caches.default

  let response = await cache.match(cacheKey)
  if (response) return response

  // 3. 替换 HTML 中的静态资源前缀
  const body = indexHtml
    .replace(/"\/assets\//g, `"${OSS_BASE}/assets/`)
    .replace(/__VITE_BASE__/g, OSS_BASE)

  response = new Response(body, {
    status: 200,
    headers: {
      'Content-Type': 'text/html; charset=utf-8',
      'Cache-Control': 'public, max-age=300', // 5 分钟边缘缓存
      'X-Content-Type-Options': 'nosniff'
    }
  })

  event.waitUntil(cache.put(cacheKey, response.clone()))
  return response
}

addEventListener('fetch', event => {
  event.respondWith(handleFetch(event))
})

步骤四:部署

npm i -g wrangler
wrangler login
wrangler deploy worker.js --name vite-ssr-edge --compatibility-date 2024-05-01

在 Cloudflare 控制台绑定已备案的自定义域 https://your-domain.com,完成 CNAME。

步骤五:验证

curl -H "Accept-Encoding: gzip" https://your-domain.com/article/123

返回的 HTML 中脚本链接应为 https://cdn.your-domain.com/vite-app/assets/main-xxx.js,且响应头带 CF-Cache-Status: HIT 即命中边缘缓存。

拓展思考

  1. 动态注入数据
    如果要做「边缘渲染 + 首屏数据」,可在 Worker 里先调同域 API(例如 https://api.your-domain.com/article/123),再把 JSON 序列化后塞进 window.__INITIAL_STATE__,实现“0 秒首屏”而无需 Node 服务器。
  2. 灰度发布
    利用 Cloudflare 的 cf-custom-hostname 与 env 变量,把新版本的 index.html 上传到 OSS 新目录,Worker 根据 Cookie 或 UA 决定走 v1/ 还是 v2/ 目录,实现国内用户无感灰度。
  3. 成本优化
    Worker 每月免费 10 万次请求,超出后 0.5 美元/百万次;静态资源走 OSS CDN 流量费约 0.15 元/GB。若日 PV 超百万,建议把 HTML 也放到 OSS,Worker 只做 302 跳转,进一步降低边缘费用。