congming_huose-apk/scripts/fix-mp-app-json.cjs

89 lines
2.8 KiB
JavaScript
Raw Normal View History

/**
* 从根目录 pages.json 重写各端微信小程序 app.json并清理已删除组件残留 GlobalNoticePush
* 解决主包 app.json 被错误合并为仅有 usingComponentspages 为空微信报错
*
* 手动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)
}