inject-manifest.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import dotenv from 'dotenv'
  2. import fs from 'fs'
  3. import { applyEdits, modify } from 'jsonc-parser'
  4. import path from 'path'
  5. /** 1️⃣ 只允许覆盖的模式(白名单) */
  6. type InjectMode = 'production_luoxin' | 'production_demo'
  7. const NEED_INJECT_MODES: InjectMode[] = ['production_luoxin', 'production_demo']
  8. /** 2️⃣ 从环境变量读取 VITE_MODE(由 cross-env 传入) */
  9. const mode = process.env.VITE_MODE as InjectMode | undefined
  10. /** 3️⃣ 根据 mode 主动加载对应的 .env 文件 */
  11. if (mode) {
  12. const ENV_FILE_MAP: Record<InjectMode, string> = {
  13. production_luoxin: '.env.production_LUOXIN',
  14. production_demo: '.env.text_DEMO',
  15. }
  16. const envFile = ENV_FILE_MAP[mode]
  17. if (envFile) {
  18. dotenv.config({
  19. path: path.resolve(process.cwd(), envFile),
  20. })
  21. }
  22. }
  23. /** 4️⃣ 非注入环境,直接退出(使用 manifest 默认值) */
  24. if (!mode || !NEED_INJECT_MODES.includes(mode)) {
  25. console.log('ℹ️ 当前模式无需注入 appid,使用 manifest.json 默认值')
  26. process.exit(0)
  27. }
  28. /** 5️⃣ 读取 appid(dotenv 已生效) */
  29. const appid = process.env.VITE_WX_APPID
  30. if (!appid) {
  31. console.error(`❌ ${mode} 缺少 VITE_WX_APPID`)
  32. process.exit(1)
  33. }
  34. /** 6️⃣ 读取 manifest.json(JSONC) */
  35. const manifestPath = path.resolve(__dirname, '../src/manifest.json')
  36. const manifestRaw = fs.readFileSync(manifestPath, 'utf-8')
  37. /** 7️⃣ 只修改 mp-weixin.appid(不破坏注释/结构) */
  38. const edits = modify(manifestRaw, ['mp-weixin', 'appid'], appid, {
  39. formattingOptions: {
  40. insertSpaces: true,
  41. tabSize: 2,
  42. },
  43. })
  44. const updatedManifest = applyEdits(manifestRaw, edits)
  45. /** 8️⃣ 写回文件 */
  46. fs.writeFileSync(manifestPath, updatedManifest)
  47. console.log(`⚠️ 当前为【${mode}】构建,appid 将被覆盖`)
  48. console.log(`✅ manifest.json appid 已覆盖: ${mode} → ${appid}`)