vite-plugin-minify-html
Version:
Minify HTML files.
45 lines (44 loc) • 1.25 kB
JavaScript
// index.ts
import { minify as minifyFn } from "html-minifier-terser";
import { createFilter } from "@rollup/pluginutils";
var PLUGIN_NAME = "vite-plugin-minify-html";
var htmlFilter = createFilter(["**/*.html"]);
function minifyOptions(options) {
const opts = options === true ? {} : options;
return {
collapseWhitespace: true,
keepClosingSlash: true,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
useShortDoctype: true,
minifyCSS: true,
...opts
};
}
async function minifyHtml(html, minify) {
if (typeof minify === "boolean" && !minify) {
return html;
}
return await minifyFn(html, minifyOptions(minify));
}
function createMinifyPlugin(minify) {
return {
name: PLUGIN_NAME,
enforce: "post",
// apply: 'build' as const,
async generateBundle(_, outputBundle) {
if (minify) {
for (const bundle of Object.values(outputBundle)) {
if (bundle.type === "asset" && htmlFilter(bundle.fileName) && typeof bundle.source === "string") {
bundle.source = await minifyHtml(bundle.source, minify);
}
}
}
}
};
}
export {
createMinifyPlugin as default
};