verify-npm-config.mjs 2.39 KB
/**
 * @file 校验 project.config.json 中 packNpmRelationList 引用的 package.json 均存在。
 * 用于排查「packageUsedCar/package.json not found」等微信开发者工具构建 npm 报错。
 */
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const projectConfigPath = path.join(root, 'project.config.json')

/**
 * @param {string} relativePath project.config 中的 packageJsonPath
 * @returns {string} 绝对路径
 */
function resolvePackageJsonPath(relativePath) {
	const normalized = relativePath.replace(/^\.\//, '')
	return path.join(root, normalized)
}

function main() {
	if (!fs.existsSync(projectConfigPath)) {
		console.error('[verify:npm-config] 缺少 project.config.json')
		console.error('请执行: git checkout HEAD -- project.config.json')
		process.exit(1)
	}

	let config
	try {
		config = JSON.parse(fs.readFileSync(projectConfigPath, 'utf8'))
	} catch (err) {
		console.error('[verify:npm-config] project.config.json 解析失败:', err.message)
		process.exit(1)
	}

	const relationList = config?.setting?.packNpmRelationList
	if (!Array.isArray(relationList) || relationList.length === 0) {
		console.log('[verify:npm-config] 未配置 packNpmRelationList,跳过检查')
		process.exit(0)
	}

	const missing = []
	const restorePaths = []

	for (const item of relationList) {
		const packageJsonPath = item?.packageJsonPath
		if (!packageJsonPath) continue

		const absolutePath = resolvePackageJsonPath(packageJsonPath)
		const relativeFromRoot = path.relative(root, absolutePath).replace(/\\/g, '/')

		if (!fs.existsSync(absolutePath)) {
			missing.push(relativeFromRoot)
			restorePaths.push(relativeFromRoot)
		}
	}

	if (missing.length > 0) {
		console.error('[verify:npm-config] 以下 package.json 不存在:')
		missing.forEach(p => console.error(`  - ${p}`))
		console.error('')
		console.error('常见原因: 未 git pull 最新代码,或本地旧 project.config 未更新。')
		console.error('恢复命令:')
		console.error(
			`  git checkout HEAD -- project.config.json ${restorePaths.join(' ')}`
		)
		console.error('')
		console.error('然后执行: npm run setup')
		console.error('并在微信开发者工具中: 工具 → 构建 npm')
		process.exit(1)
	}

	console.log('[verify:npm-config] 通过,共检查', relationList.length, '项 npm 配置')
	process.exit(0)
}

main()