如何在 SSR 渲染过程中注入由 Vite 生成的 CSS 和 JS 资源?

解读

国内主流公司(阿里、字节、美团、拼多多)的 Node 层 SSR 方案,99% 会把“首屏直出 HTML”拆成三步:

  1. 构建阶段:Vite 把源码打成 client 与 server 两份产物;
  2. 请求阶段:Node 服务用 server-bundle 把组件渲染成纯 HTML 字符串;
  3. 注入阶段:把 Vite 在构建时收集到的 CSS/JS 资源链接,拼进 HTML 模板,保证浏览器拿到完整可交互页面。

面试时,如果只说“用 vite-plugin-ssr 就行”,会被认为“只会调包”;如果手写实现,必须答出“开发态用 manifest,生产态用 manifest.json,中间层用 transformIndexHtml”这三层差异,才能体现“源码级”理解。

知识点

  1. manifest 机制
    Vite 在 build.rollupOptions.output.manualChunks 场景下会生成 assets 与 chunks 的映射表,server 端靠这张表才能找到本次渲染到底依赖了哪几个 css/js 文件。

  2. 开发态(dev)

    • 没有物理文件,ViteDevServer 通过 pluginContainer 在内存里维护模块图;
    • 用 ssrLoadModule 拉取入口后,通过 server.moduleGraph 反向收集当前渲染树用到的 URL;
    • 用 vite.transformIndexHtml 把 <!DOCTYPE html> 模板中的 <!--vite-css-->、<!--vite-js--> 占位符替换成带 HMR 端口的绝对路径。
  3. 生产态(prod)

    • build.ssrManifest 开关会额外生成 ssr-manifest.json,记录每个入口 chunk 对应的 css 与 asset 列表;
    • Node 端先 readFileSync 该 json,再根据 renderToString 返回的 “收集到的模块 id 数组” 做交集,得到本次渲染真正需要的文件;
    • 按公司 CDN 规范拼成 //cdn.xxx.com/xxx.css 后,插入到模板 <head> 与 <body> 尾部,并补上 preload/prefetch 优化标签。
  4. 安全与性能

    • 必须对文件名做 nonce 或 integrity 校验,防止 CDN 劫持;
    • 不能把整个 manifest 一次性注入,否则首屏会多 50 KB 冗余资源;
    • 对 CSS 做 critical 提取时,要把内联 critical 与异步非 critical 拆成两段,保证 Lighthouse 首屏指标 < 1.5 s。

答案

开发环境(以 Express 为例):

// server.js
import { createServer as createViteServer } from 'vite'

async function createServer() {
  const app = express()
  const vite = await createViteServer({
    server: { middlewareMode: true },
    appType: 'custom'
  })
  app.use(vite.middlewares)

  app.get('*', async (req, res) => {
    const template = await vite.transformIndexHtml(
      req.url,
      fs.readFileSync(path.resolve('index.html'), 'utf-8')
    )
    const { render } = await vite.ssrLoadModule('/src/entry-server.js')
    const { html: appHtml, deps } = render(req.url) // deps 是自定义收集的模块 id
    const cssTags = deps
      .map(id => vite.moduleGraph.getModuleById(id)?.url)
      .filter(Boolean)
      .map(url => `<link rel="stylesheet" href="${url}">`)
      .join('')
    const html = template
      .replace('<!--app-html-->', appHtml)
      .replace('<!--app-css-->', cssTags)
    res.status(200).set({ 'content-type': 'text/html' }).end(html)
  })
}

生产环境(以 Koa 为例):

// prod-server.js
const manifest = JSON.parse(fs.readFileSync('dist/ssr-manifest.json', 'utf-8'))
const template = fs.readFileSync('dist/client/index.html', 'utf-8')

app.use(async ctx => {
  const { render } = require('./dist/server/entry-server.js')
  const { html: appHtml, moduleIds } = render(ctx.path)
  const seen = new Set()
  const css = []
  const js  = []
  moduleIds.forEach(id => {
    const chunks = manifest[id] || []
    chunks.forEach(file => {
      if (seen.has(file)) return
      seen.add(file)
      if (file.endsWith('.css')) css.push(`<link rel="stylesheet" href="${cdnHost}/${file}">`)
      if (file.endsWith('.js'))  js.push(`<link rel="modulepreload" href="${cdnHost}/${file}">`)
    })
  })
  const fullHtml = template
    .replace('<!--app-css-->', css.join(''))
    .replace('<!--app-js-->', js.join(''))
    .replace('<!--app-html-->', appHtml)
  ctx.body = fullHtml
})

关键点:

  • 开发态用 vite.transformIndexHtml 保证 HMR 端口正确;
  • 生产态用 ssr-manifest.json 做“按需收集”,避免全量注入;
  • 所有 URL 走公司统一 CDN 域名,并加 crossorigin=anonymous 防止 Cookies 泄露。

拓展思考

  1. 微前端场景:子应用独立构建,主应用 SSR 时需要把子应用的 manifest 也合并进来,如何设计版本锁与缓存 Key?
  2. 流式渲染:renderToPipeableStream 把 HTML 分段刷给浏览器,CSS 注入时机必须早于第一次 flush,否则会出现 FOUC,如何与 Vite 的异步 chunk 加载协调?
  3. Edge Runtime:在阿里云的 Node.js 16 边缘函数里,readFileSync 不可用,需要把 manifest 打包进 bundle,如何既保证 tree-shaking 又保证运行时性能?
  4. 低版本浏览器:公司仍需支持 Chrome 48(内核 48),Vite 默认输出 ES2020,如何降级并注入 legacy-polyfill 的 JS 资源,同时不阻塞首屏?