68 lines
2.1 KiB
JavaScript
68 lines
2.1 KiB
JavaScript
/**
|
||
* 微信小程序:构建完成后用 pages.json 覆盖写 app.json,并清理已删除组件的残留文件,
|
||
* 避免主包 app.json 被误合并为「仅有 usingComponents、无 pages」。
|
||
* HBuilderX 若走 vue-cli 链时会加载本文件;纯内置编译无此文件时,请执行 npm run mp:fix-app-json
|
||
*/
|
||
const path = require('path')
|
||
const fs = require('fs')
|
||
const { execFileSync } = require('child_process')
|
||
|
||
const fixScript = path.join(__dirname, 'scripts', 'fix-mp-app-json.cjs')
|
||
|
||
/** 从 manifest.json 解析 versionName(支持文件内注释) */
|
||
function readManifestVersionName() {
|
||
const manifestPath = path.join(__dirname, 'manifest.json')
|
||
try {
|
||
const raw = fs.readFileSync(manifestPath, 'utf8')
|
||
const nameMatch = raw.match(/"versionName"\s*:\s*"([^"]+)"/)
|
||
if (nameMatch) return nameMatch[1]
|
||
} catch (e) {
|
||
console.warn('[vue.config] read manifest version:', e && e.message)
|
||
}
|
||
return '1.0.1'
|
||
}
|
||
|
||
function runFix() {
|
||
if (!fs.existsSync(fixScript)) return
|
||
try {
|
||
execFileSync(process.execPath, [fixScript], { cwd: __dirname, stdio: 'pipe' })
|
||
} catch (e) {
|
||
// 不打断主构建
|
||
}
|
||
}
|
||
|
||
class FixMpWxAppJsonPlugin {
|
||
apply(compiler) {
|
||
compiler.hooks.done.tap('FixMpWxAppJson', (stats) => {
|
||
if (stats && stats.hasErrors && stats.hasErrors()) return
|
||
runFix()
|
||
})
|
||
}
|
||
}
|
||
|
||
module.exports = {
|
||
chainWebpack(config) {
|
||
try {
|
||
if (config && typeof config.plugin === 'function') {
|
||
const manifestVersion = readManifestVersionName()
|
||
config.plugin('define').tap((definitions) => {
|
||
const def = definitions[0] || {}
|
||
def['__APP_MANIFEST_VERSION__'] = JSON.stringify(manifestVersion)
|
||
definitions[0] = def
|
||
return definitions
|
||
})
|
||
}
|
||
} catch (e) {
|
||
console.warn('[vue.config] define manifest version:', e && e.message)
|
||
}
|
||
try {
|
||
if (!config || typeof config.plugin !== 'function') return
|
||
const name = 'fix-mp-wx-app-json'
|
||
if (config.plugins && config.plugins.has && config.plugins.has(name)) return
|
||
config.plugin(name).use(FixMpWxAppJsonPlugin, [])
|
||
} catch (e) {
|
||
console.warn('[fix-mp] vue.config 链式插件未生效(可改用手动执行 npm run mp:fix-app-json)', e && e.message)
|
||
}
|
||
},
|
||
}
|