Files
daedalOS/scripts/minifyJs.js

74 lines
1.9 KiB
JavaScript
Raw Normal View History

2022-07-27 20:25:26 -07:00
const { readdirSync, readFileSync, statSync, writeFileSync } = require("fs");
const { minify } = require("terser");
const { extname, join } = require("path");
const OUT_PATH = "out";
const JS_MINIFIER_CONFIG = {
compress: true,
ecma: 2021,
mangle: true,
2023-09-21 23:20:42 -07:00
output: {
comments: false,
},
sourceMap: false,
2022-07-27 20:25:26 -07:00
};
2025-03-14 19:33:20 -07:00
const workerRegEx =
2025-03-15 09:18:49 -07:00
/new Worker\(\w+\.\w+\(new URL\(\w+\.\w+\+\w+\.\w+\(\d+\),\w+\.\w+\)\),\{name:"(.+)"\}\)/;
2025-03-14 19:33:20 -07:00
const inlineIndexWorkers = (code) => {
const [, workerName] = code.match(workerRegEx) || [];
if (workerName) {
const workerFilename = readdirSync(
join(OUT_PATH, "_next/static/chunks")
).find((entry) => entry.startsWith(`${workerName}.`));
const workerSource = readFileSync(
join(OUT_PATH, "_next/static/chunks", workerFilename)
);
const base64Worker = Buffer.from(workerSource).toString("base64");
return code.replace(
workerRegEx,
`new Worker("data:application/javascript;base64,${base64Worker}",{name:"${workerName}"})`
);
}
return code;
};
2022-07-27 20:25:26 -07:00
const minifyJsFiles = (path) =>
Promise.all(
readdirSync(path).map(async (entry) => {
const fullPath = join(path, entry);
const stats = statSync(fullPath);
if (stats.isDirectory()) {
minifyJsFiles(fullPath);
2023-06-30 15:44:36 -07:00
} else if (extname(entry).toLowerCase() === ".js") {
2022-07-27 20:25:26 -07:00
const js = readFileSync(fullPath);
2025-03-14 19:33:20 -07:00
let { code: minifiedJs, error } = await minify(
2022-07-27 20:25:26 -07:00
js.toString(),
JS_MINIFIER_CONFIG
);
if (!error && minifiedJs?.length > 0) {
2025-03-14 19:33:20 -07:00
if (entry.startsWith("index-")) {
const changedCode = inlineIndexWorkers(minifiedJs);
if (minifiedJs === changedCode) {
throw new Error("Inlining worker failed!");
}
minifiedJs = changedCode;
}
2022-07-27 20:25:26 -07:00
writeFileSync(fullPath, minifiedJs);
}
}
})
);
minifyJsFiles(OUT_PATH);