53 lines
1.9 KiB
JavaScript
53 lines
1.9 KiB
JavaScript
// 前端资源防陈旧缓存:chunk 内容变化 → 文件名跟着变(内容 hash 前 8 位),
|
|
// 浏览器按文件名缓存 immutable 一年,改名后会当新文件拉取。
|
|
// 幂等:内容未变则文件名已匹配,直接跳过。
|
|
const fs = require("fs");
|
|
const path = require("path");
|
|
const crypto = require("crypto");
|
|
|
|
const CHUNK_DIR = "/app/.next/static/chunks";
|
|
const NEXT_DIR = "/app/.next";
|
|
|
|
function findChunk() {
|
|
const files = fs.readdirSync(CHUNK_DIR).filter(f => /^402-.*\.js$/.test(f));
|
|
if (files.length !== 1) { console.log("cachebust: expected 1 402 chunk, found", files); return null; }
|
|
return path.join(CHUNK_DIR, files[0]);
|
|
}
|
|
|
|
const oldPath = findChunk();
|
|
if (!oldPath) process.exit(0);
|
|
|
|
const content = fs.readFileSync(oldPath, "utf8");
|
|
const hash = crypto.createHash("md5").update(content).digest("hex").slice(0, 8);
|
|
const oldName = path.basename(oldPath);
|
|
const newName = "402-" + hash + ".js";
|
|
|
|
// 已按内容 hash 命名 → 无需处理
|
|
if (oldName === newName) { console.log("cachebust: up-to-date", newName); process.exit(0); }
|
|
|
|
const newPath = path.join(CHUNK_DIR, newName);
|
|
fs.writeFileSync(newPath, content);
|
|
console.log("cachebust: wrote", newName);
|
|
|
|
// 替换所有引用
|
|
let refs = 0, files = 0;
|
|
function walk(dir) {
|
|
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
const p = path.join(dir, e.name);
|
|
if (e.isDirectory()) { walk(p); continue; }
|
|
if (!/\.(js|json)$/.test(e.name)) continue;
|
|
if (p === newPath) continue;
|
|
let s;
|
|
try { s = fs.readFileSync(p, "utf8"); } catch (err) { continue; }
|
|
if (!s.includes(oldName)) continue;
|
|
fs.writeFileSync(p, s.split(oldName).join(newName));
|
|
refs++; files++;
|
|
}
|
|
}
|
|
walk(NEXT_DIR);
|
|
console.log("cachebust: replaced refs in", files, "file(s)");
|
|
|
|
// 删旧文件(放在最后,避免中途失败导致引用悬空)
|
|
fs.unlinkSync(oldPath);
|
|
console.log("cachebust: removed", oldName, "->", newName);
|