From 1f42981fd4a01132a7e36f268739eba45513f3c9 Mon Sep 17 00:00:00 2001 From: yuantao Date: Tue, 28 Oct 2025 11:52:58 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=EF=BC=9Avite=E7=BC=96?= =?UTF-8?q?=E8=AF=91=E9=85=8D=E7=BD=AE=E5=9C=A8=E7=83=AD=E9=87=8D=E8=BD=BD?= =?UTF-8?q?=E7=9A=84=E6=83=85=E5=86=B5=E4=B8=8B=E5=AF=BC=E8=87=B4=E5=86=85?= =?UTF-8?q?=E5=AD=98=E6=BA=A2=E5=87=BA=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- vite.config.js | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/vite.config.js b/vite.config.js index 6f2d032..3eb7ab5 100644 --- a/vite.config.js +++ b/vite.config.js @@ -1,14 +1,26 @@ import { defineConfig } from 'vite' import uni from '@dcloudio/vite-plugin-uni' import { resolve } from 'path' -import { readFileSync, writeFileSync } from 'fs' +import { readFileSync, writeFileSync, existsSync, unlinkSync } from 'fs' import dotenv from 'dotenv' // 自定义插件:替换 manifest.json 中的 appid +// 仅在通过HBuilder首次编译时执行,避免热重载时重复执行导致内存占用高 function replaceManifestAppid() { return { name: 'replace-manifest-appid', buildStart() { + // 检查是否通过HBuilder编译 + // 检查是否已经执行过插件 + const manifestUpdatedFlag = resolve(__dirname, '.manifest-updated') + const isFirstCompile = !existsSync(manifestUpdatedFlag) + + // 仅首次编译时执行 + if (!isFirstCompile) { + console.log('跳过 manifest appid 更新(已执行过首次编译)') + return + } + // 获取环境变量,明确指定路径为项目根目录 dotenv.config({ path: resolve(__dirname, '.env') }) const appid = process.env.VITE_APPID @@ -18,19 +30,19 @@ function replaceManifestAppid() { // 读取 manifest.json 文件 const manifestPath = resolve(__dirname, 'manifest.json') let manifestContent = readFileSync(manifestPath, 'utf-8') - // 解析 JSON const manifest = JSON.parse(manifestContent) - // 替换 manifest.appid = uni_appId + if (manifest['mp-weixin']) { manifest['mp-weixin'].appid = appid } // 写回文件 writeFileSync(manifestPath, JSON.stringify(manifest, null, 4)) - + // 创建标记文件,表示已执行过插件 + writeFileSync(manifestUpdatedFlag, 'Manifest updated by HBuilder first compile') console.log(`Manifest appid 已更新为: ${uni_appId}`) console.log(`Manifest mp-weixin appid 已更新为: ${appid}`) } else { @@ -40,8 +52,17 @@ function replaceManifestAppid() { } } +// 检查是否通过HBuilder编译,决定是否启用插件 +const manifestUpdatedFlag = resolve(__dirname, '.manifest-updated') + +if (existsSync(manifestUpdatedFlag)) { + unlinkSync(manifestUpdatedFlag) + console.log('已清理 manifest 更新标记文件') +} + +const plugins = manifestUpdatedFlag ? [replaceManifestAppid(), uni()] : [uni()] export default defineConfig({ - plugins: [replaceManifestAppid(), uni()], + plugins, resolve: { alias: { '@': '/src',