File size: 2,672 Bytes
232c957 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | const fs = require("fs");
const path = require("path");
const ROOT = __dirname;
function walkHtmlFiles(rootDir) {
const result = [];
const stack = [rootDir];
while (stack.length > 0) {
const current = stack.pop();
const entries = fs.readdirSync(current, { withFileTypes: true });
for (const entry of entries) {
const full = path.join(current, entry.name);
if (entry.isDirectory()) {
stack.push(full);
} else if (entry.isFile() && entry.name.toLowerCase().endsWith(".html")) {
result.push(full);
}
}
}
result.sort();
return result;
}
function externalizeInlineScripts(htmlPath) {
const html = fs.readFileSync(htmlPath, "utf8");
const pattern = /<script(?![^>]*\bsrc\b)([^>]*)>([\s\S]*?)<\/script>/gi;
const matches = [...html.matchAll(pattern)];
if (matches.length === 0) {
return { changed: false, extracted: 0, bytesBefore: Buffer.byteLength(html, "utf8"), bytesAfter: Buffer.byteLength(html, "utf8") };
}
const dir = path.dirname(htmlPath);
const base = path.basename(htmlPath, ".html");
let index = 1;
let nextHtml = html;
for (const match of matches) {
const fullMatch = match[0];
const attrs = match[1] || "";
const content = match[2] || "";
if (!content.trim()) {
continue;
}
const jsName = `${base}.inline${String(index).padStart(2, "0")}.js`;
const jsPath = path.join(dir, jsName);
const normalized = content.replace(/^\r?\n/, "").replace(/\s*$/, "") + "\n";
fs.writeFileSync(jsPath, normalized, "utf8");
const replacement = `<script${attrs} src="./${jsName}"></script>`;
nextHtml = nextHtml.replace(fullMatch, replacement);
index += 1;
}
fs.writeFileSync(htmlPath, nextHtml, "utf8");
return {
changed: true,
extracted: index - 1,
bytesBefore: Buffer.byteLength(html, "utf8"),
bytesAfter: Buffer.byteLength(nextHtml, "utf8")
};
}
function main() {
const htmlFiles = walkHtmlFiles(ROOT).filter((file) => !file.endsWith("externalize_inline_scripts.js"));
let changedFiles = 0;
let extractedScripts = 0;
let bytesBefore = 0;
let bytesAfter = 0;
for (const htmlPath of htmlFiles) {
const stats = externalizeInlineScripts(htmlPath);
bytesBefore += stats.bytesBefore;
bytesAfter += stats.bytesAfter;
if (stats.changed) {
changedFiles += 1;
extractedScripts += stats.extracted;
}
}
const report = {
scannedHtml: htmlFiles.length,
changedHtml: changedFiles,
extractedScripts,
bytesBefore,
bytesAfter,
reducedBytes: Math.max(0, bytesBefore - bytesAfter)
};
console.log(JSON.stringify(report, null, 2));
}
main();
|