/** * 修正 Plasmo build 后 manifest.json 中 web_accessible_resources 引用不存在文件的问题 * 逻辑:遍历 manifest 中所有引用的资源文件名,如果在 build 目录中不存在, * 则尝试用「同前缀 + 同后缀」的实际文件替换,找不到则移除该条目 */ const fs = require("fs") const path = require("path") const buildDir = path.resolve(__dirname, "../build/chrome-mv3-prod") const manifestPath = path.join(buildDir, "manifest.json") if (!fs.existsSync(manifestPath)) { console.error("[fix-manifest] manifest.json 不存在,跳过") process.exit(0) } const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8")) // 递归获取 build 目录下所有文件的相对路径 function getAllFiles(dir, baseDir, result = []) { const entries = fs.readdirSync(dir, { withFileTypes: true }) for (const entry of entries) { const fullPath = path.join(dir, entry.name) if (entry.isDirectory()) { getAllFiles(fullPath, baseDir, result) } else { result.push(path.relative(baseDir, fullPath).replace(/\\/g, "/")) } } return result } const actualFiles = getAllFiles(buildDir, buildDir) if (!manifest.web_accessible_resources) { console.log("[fix-manifest] 无 web_accessible_resources,无需修正") process.exit(0) } let modified = false manifest.web_accessible_resources.forEach((entry) => { if (!entry.resources) return const newResources = [] for (const resource of entry.resources) { if (actualFiles.includes(resource)) { // 文件存在,保留 newResources.push(resource) } else { // 文件不存在,尝试匹配:取文件名前缀(第一个.之前)和后缀(最后一个.之后) const fileName = resource.split("/").pop() const dirPart = resource.includes("/") ? resource.substring(0, resource.lastIndexOf("/") + 1) : "" const parts = fileName.split(".") const prefix = parts[0] // 如 sidebar const ext = parts[parts.length - 1] // 如 css // 在实际文件中找同前缀同后缀的(考虑目录层级) const match = actualFiles.find((f) => { const fName = f.split("/").pop() const fParts = fName.split(".") return fParts[0] === prefix && fParts[fParts.length - 1] === ext }) if (match) { // 检查是否已经在 content_scripts.css 或其他地方被引用了(避免重复) console.log(`[fix-manifest] 替换: ${resource} -> ${match}`) newResources.push(match) modified = true } else { console.log(`[fix-manifest] 移除不存在的资源: ${resource}`) modified = true } } } entry.resources = newResources }) if (modified) { fs.writeFileSync(manifestPath, JSON.stringify(manifest), "utf-8") console.log("[fix-manifest] manifest.json 已修正完成") } else { console.log("[fix-manifest] 所有资源文件均存在,无需修正") }