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