如何在 Vite 中动态生成 manifest.json 文件并注入应用名称、图标、主题色?

解读

国内前端面试常把“PWA 能力”与“工程化能力”混在一道题里考察。
题目表面问“生成 manifest.json”,实则想看候选人是否理解:

  1. Vite 的“插件即中间件”思想,能在 dev 与 build 阶段同时干预文件系统;
  2. 如何在不写死静态文件的前提下,把 package.json 里的 name、version 或 CI 注入的变量映射到 PWA 配置;
  3. 图标、主题色等静态资源如何走 Vite 的“资源管道”拿到带哈希的最终 URL,再写回 manifest。
    如果候选人只回答“用 vite-plugin-pwa 就行”,会被追问“不用插件怎么手写”“如何兼容多环境”“如何热更新”,因此必须给出“原生插件写法 + 可选社区方案”两层答案。

知识点

  1. Vite 插件生命周期:config、configResolved、generateBundle、writeBundle、configureServer。
  2. 虚拟模块:通过 \0 前缀拦截请求,dev 时动态返回内容,避免落盘。
  3. 资源 URL 解析:调用 config.resolve.alias + this.getFileName 拿到带哈希的图标路径。
  4. 多环境注入:借助 loadEnv(mode, process.cwd(), '') 把 .env.production 中的 VITE_APP_NAME 读进来。
  5. MIME 与响应头:dev-server 返回 application/manifest+json; charset=utf-8,确保 Chrome 识别。
  6. 缓存策略:build 阶段把 manifest 作为资源文件写入,配合 workbox 缓存策略,文件名带哈希防止 CDN 缓存旧版本。
  7. 国内 CDN 合规:图标路径需使用相对路径或同域路径,否则微信、钉钉内置浏览器会拦截外域 manifest。

答案

  1. 手写原生插件(最通用,面试加分)
    在项目根建 plugins/vite-plugin-manifest.js:
import { readFileSync } from 'fs'
import { resolve } from 'path'

export default function manifestPlugin(options = {}) {
  const virtual = 'virtual:manifest'
  const resolved = '\0' + virtual
  return {
    name: 'vite:manifest-json',
    configResolved(config) {
      // 把环境变量读进来
      const { name = 'ViteApp', theme_color = '#1890ff' } = {
        ...config.env,
        ...options
      }
      this._name = name
      this._theme = theme_color
    },
    resolveId(id) {
      if (id === virtual) return resolved
    },
    load(id) {
      if (id !== resolved) return
      // 图标走 Vite 资源管道,拿到最终 URL
      const icon192 = '/icons/icon-192.png'   // build 后会带哈希
      const icon512 = '/icons/icon-512.png'
      const manifest = {
        name: this._name,
        short_name: this._name,
        start_url: '/',
        display: 'standalone',
        background_color: '#ffffff',
        theme_color: this._theme,
        icons: [
          { src: icon192, sizes: '192x192', type: 'image/png' },
          { src: icon512, sizes: '512x512', type: 'image/png' }
        ]
      }
      return `export default ${JSON.stringify(manifest)}`
    },
    generateBundle(_, bundle) {
      // build 阶段把 JSON 落盘
      const code = this.getModuleInfo('\0virtual:manifest').code
      const obj = JSON.parse(code.match(/export default (.+)/)[1])
      this.emitFile({
        type: 'asset',
        fileName: 'manifest.json',
        source: JSON.stringify(obj, null, 2)
      })
    },
    configureServer(server) {
      // dev 阶段拦截 /manifest.json 请求
      server.middlewares.use('/manifest.json', (req, res, next) => {
        const mod = server.moduleGraph.getModuleById(resolved)
        if (!mod) return next()
        const manifest = JSON.parse(mod.info.code.match(/export default (.+)/)[1])
        res.setHeader('Content-Type', 'application/manifest+json; charset=utf-8')
        res.end(JSON.stringify(manifest, null, 2))
      })
    }
  }
}

在 vite.config.ts 使用:

import manifestPlugin from './plugins/vite-plugin-manifest'

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  return {
    plugins: [
      manifestPlugin({
        name: env.VITE_APP_NAME,
        theme_color: env.VITE_THEME_COLOR
      })
    ]
  }
})
  1. 社区方案(答完手写后可补充)
    安装 vite-plugin-pwa,在 vite.config.ts 里:
import { VitePWA } from 'vite-plugin-pwa'

VitePWA({
  manifest: {
    name: process.env.VITE_APP_NAME,
    theme_color: process.env.VITE_THEME_COLOR,
    icons: [{ src: 'icons/icon-192.png', sizes: '192x192', type: 'image/png' }]
  },
  injectRegister: 'auto'
})

面试官若追问“不用插件怎么办”,即可把前面原生插件代码背出来,体现“知其然也知其所以然”。

拓展思考

  1. 多语言品牌:在 CI 阶段根据 process.env.BRAND 注入不同名称与图标,插件里用 this._brand 做条件分支,一套代码打包出“国内版”“国际版”两套 manifest。
  2. 图标自动生成:结合 vite-plugin-imagemin 与 sharp,在 buildStart 钩子把 1024×1024 的源图自动裁切出 192、512、180、167 等多尺寸,并返回带哈希路径,无需设计师反复导出。
  3. 热更新:dev 阶段如果设计师替换了 public/icons 下的文件,通过 server.ws.send({ type: 'full-reload' }) 让浏览器重新拉取 manifest,实现“图标一改,PWA 立刻刷新”。
  4. 合规检测:插件里增加 manifest.icons.forEach 校验,若发现外域图标或小于 144×144,直接 this.error 抛错,防止上线后被应用商店驳回。