daedalOS/scripts/minifyHtml.js
2022-03-07 20:24:31 -08:00

50 lines
1.5 KiB
JavaScript

const { readdirSync, readFileSync, writeFileSync } = require("fs");
const { minify } = require("html-minifier-terser");
const { extname, join } = require("path");
const OUT_PATH = "out";
const HTML_MINIFIER_CONFIG = {
collapseBooleanAttributes: true,
collapseInlineTagWhitespace: true,
collapseWhitespace: true,
decodeEntities: true,
includeAutoGeneratedTags: false,
minifyJS: true,
minifyURLs: true,
processConditionalComments: true,
processScripts: ["text/html"],
removeAttributeQuotes: true,
removeComments: true,
removeEmptyAttributes: true,
removeOptionalTags: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
sortAttributes: true,
sortClassName: true,
trimCustomFragments: true,
useShortDoctype: true,
};
const CODE_REMOVE_FUNCTIONS = [
(html) => html.replace(/<noscript (.*)><\/noscript>/, ""),
(html) => html.replace(/<script (.*) nomodule=""><\/script>/, ""),
(html) =>
html.replace(/<style data-styled="" data-styled-version=(.*)>/, "<style>"),
];
readdirSync(OUT_PATH).forEach(async (entry) => {
if (extname(entry) === ".html") {
const filPath = join(OUT_PATH, entry);
const html = await readFileSync(filPath);
let minifiedHtml = await minify(html.toString(), HTML_MINIFIER_CONFIG);
CODE_REMOVE_FUNCTIONS.forEach(
(codeFunction) => (minifiedHtml = codeFunction(minifiedHtml))
);
await writeFileSync(filPath, minifiedHtml);
}
});