dbl-utils
Version:
Utilities for dbl, adba and others projects
53 lines (52 loc) • 2.48 kB
JavaScript
#! bin/node
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
require("dotenv").config({});
import * as fs from "fs";
import { PurgeCSS } from "purgecss";
import prettier from "prettier";
/**
* Purges unused CSS based on HTML content.
*
* @param cssFilePath - Path to the CSS file generated by the build.
* @param htmlDirPath - Directory containing the generated HTML files.
* @param outputCssFilePath - Path to save the purged CSS.
*/
const purgeCss = (cssFilePath, htmlDirPath, outputCssFilePath) => __awaiter(void 0, void 0, void 0, function* () {
try {
// Ensure input files exist
if (!fs.existsSync(cssFilePath))
throw new Error("CSS file not found");
if (!fs.existsSync(htmlDirPath))
throw new Error("HTML directory not found");
console.log("Purging unused CSS...");
// Step 1: Use PurgeCSS to remove unused styles
const purgeCSSResult = yield new PurgeCSS().purge({
content: [`${htmlDirPath}`], // Analyze all HTML files in the directory
css: [cssFilePath], // CSS file generated by the build,
});
if (!purgeCSSResult || purgeCSSResult.length === 0) {
throw new Error("PurgeCSS failed to produce results.");
}
const purgedCss = purgeCSSResult[0].css;
console.log("Formatting CSS...");
// Step 2: Format CSS using Prettier
const formattedCss = yield prettier.format(purgedCss, { parser: "css" });
console.log("Writing purged CSS to output...");
// Step 3: Write the formatted CSS to the output file
fs.writeFileSync(outputCssFilePath, formattedCss, "utf8");
console.log(`Purged CSS written to: ${outputCssFilePath}`);
}
catch (error) {
console.error(error);
process.exit(1);
}
});
export default purgeCss;