修复:vite编译配置在热重载的情况下导致内存溢出的问题

This commit is contained in:
yuantao
2025-10-28 11:52:58 +08:00
parent ad0f64a48a
commit 1f42981fd4

View File

@@ -1,14 +1,26 @@
import { defineConfig } from 'vite' import { defineConfig } from 'vite'
import uni from '@dcloudio/vite-plugin-uni' import uni from '@dcloudio/vite-plugin-uni'
import { resolve } from 'path' import { resolve } from 'path'
import { readFileSync, writeFileSync } from 'fs' import { readFileSync, writeFileSync, existsSync, unlinkSync } from 'fs'
import dotenv from 'dotenv' import dotenv from 'dotenv'
// 自定义插件:替换 manifest.json 中的 appid // 自定义插件:替换 manifest.json 中的 appid
// 仅在通过HBuilder首次编译时执行避免热重载时重复执行导致内存占用高
function replaceManifestAppid() { function replaceManifestAppid() {
return { return {
name: 'replace-manifest-appid', name: 'replace-manifest-appid',
buildStart() { 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') }) dotenv.config({ path: resolve(__dirname, '.env') })
const appid = process.env.VITE_APPID const appid = process.env.VITE_APPID
@@ -18,19 +30,19 @@ function replaceManifestAppid() {
// 读取 manifest.json 文件 // 读取 manifest.json 文件
const manifestPath = resolve(__dirname, 'manifest.json') const manifestPath = resolve(__dirname, 'manifest.json')
let manifestContent = readFileSync(manifestPath, 'utf-8') let manifestContent = readFileSync(manifestPath, 'utf-8')
// 解析 JSON // 解析 JSON
const manifest = JSON.parse(manifestContent) const manifest = JSON.parse(manifestContent)
// 替换 // 替换
manifest.appid = uni_appId manifest.appid = uni_appId
if (manifest['mp-weixin']) { if (manifest['mp-weixin']) {
manifest['mp-weixin'].appid = appid manifest['mp-weixin'].appid = appid
} }
// 写回文件 // 写回文件
writeFileSync(manifestPath, JSON.stringify(manifest, null, 4)) writeFileSync(manifestPath, JSON.stringify(manifest, null, 4))
// 创建标记文件,表示已执行过插件
writeFileSync(manifestUpdatedFlag, 'Manifest updated by HBuilder first compile')
console.log(`Manifest appid 已更新为: ${uni_appId}`) console.log(`Manifest appid 已更新为: ${uni_appId}`)
console.log(`Manifest mp-weixin appid 已更新为: ${appid}`) console.log(`Manifest mp-weixin appid 已更新为: ${appid}`)
} else { } 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({ export default defineConfig({
plugins: [replaceManifestAppid(), uni()], plugins,
resolve: { resolve: {
alias: { alias: {
'@': '/src', '@': '/src',