/** * 从根目录 pages.json 重写各端微信小程序 app.json,并清理已删除组件残留(如 GlobalNoticePush)。 * 解决:主包 app.json 被错误合并为仅有 usingComponents、pages 为空(微信报错)。 * * 手动:node scripts/fix-mp-app-json.cjs * 或:npm run mp:fix-app-json * 编译时:由 vue.config.js 在构建完成后自动执行(若 HBuilderX 走 vue-cli 则生效)。 */ const fs = require('fs') const path = require('path') const root = path.join(__dirname, '..') const sourceVue = path.join(root, 'common/components/GlobalNoticePush.vue') function walkRemoveGhost(dir) { if (!fs.existsSync(dir)) return const names = fs.readdirSync(dir, { withFileTypes: true }) for (const n of names) { const p = path.join(dir, n.name) if (n.isDirectory()) { walkRemoveGhost(p) } else if (/GlobalNoticePush\./.test(n.name)) { try { fs.unlinkSync(p) console.log('[fix-mp] 删除残留:', path.relative(root, p)) } catch (e) {} } } } function removeGhostGlobalNotice() { if (fs.existsSync(sourceVue)) return // 源码已无该组件,删除 dist 里旧产物,避免合并器再次引用 const candidates = [ path.join(root, 'unpackage/dist/dev/mp-weixin/common/components'), path.join(root, 'unpackage/dist/build/mp-weixin/common/components'), ] for (const c of candidates) { walkRemoveGhost(c) } // 旧 sourcemap const sm = path.join(root, 'unpackage/dist/dev/.sourcemap/mp-weixin/common/components') walkRemoveGhost(sm) } function buildPayload() { const pj = JSON.parse(fs.readFileSync(path.join(root, 'pages.json'), 'utf8')) const gs = pj.globalStyle || {} const window = { navigationBarTextStyle: gs.navigationBarTextStyle || 'black', navigationBarTitleText: gs.navigationBarTitleText || '', navigationBarBackgroundColor: gs.navigationBarBackgroundColor || '#F8F8F8', backgroundColor: gs.backgroundColor || '#F8F8F8', } return { pages: pj.pages.map((p) => p.path), window, subPackages: (pj.subPackages || []).map((sp) => ({ root: sp.root, pages: sp.pages.map((p) => p.path), })), style: 'v2', } } function writeAppJson(outPath, payload) { fs.mkdirSync(path.dirname(outPath), { recursive: true }) fs.writeFileSync(outPath, JSON.stringify(payload, null, '\t'), 'utf8') console.log('[fix-mp] 已写入', path.relative(root, outPath)) } function main() { removeGhostGlobalNotice() const payload = buildPayload() // 必写 dev(可 mkdir;首次编译后也能用) writeAppJson(path.join(root, 'unpackage/dist/dev/mp-weixin/app.json'), payload) const buildDir = path.join(root, 'unpackage/dist/build/mp-weixin') if (fs.existsSync(buildDir)) { writeAppJson(path.join(buildDir, 'app.json'), payload) } } try { main() } catch (e) { console.error('[fix-mp] 失败:', e) process.exit(1) }