HTML extractor for PurgeCSS. This extractor parses HTML files and extracts used selectors with detailed information about tags, classes, IDs, and attributes.
npm install purgecss-from-html --save-devimport PurgeCSS from "purgecss";
import purgeFromHtml from "purgecss-from-html";
const result = await new PurgeCSS().purge({
content: ["**/*.html"],
css: ["**/*.css"],
extractors: [
{
extractor: purgeFromHtml,
extensions: ["html"],
},
],
});You can also use the extractor standalone to extract selectors from HTML content:
import purgeFromHtml from "purgecss-from-html";
const html = `
<div class="container">
<h1 id="title" data-section="hero">Hello World</h1>
<button class="btn btn-primary">Click me</button>
</div>
`;
const result = purgeFromHtml(html);
console.log(result);
// {
// attributes: {
// names: ["class", "id", "data-section", "class"],
// values: ["container", "title", "hero", "btn", "btn-primary"]
// },
// classes: ["container", "btn", "btn-primary"],
// ids: ["title"],
// tags: ["html", "head", "body", "div", "h1", "button"],
// undetermined: []
// }Parses HTML content and returns detailed selector information.
content- HTML code as a string
An ExtractorResultDetailed object containing:
attributes.names- Array of attribute names found in the HTMLattributes.values- Array of attribute values (split by spaces)classes- Array of class names extracted fromclassattributesids- Array of IDs extracted fromidattributestags- Array of HTML tag names usedundetermined- Array of selectors that couldn't be categorized
This extractor uses parse5 to parse the HTML into an AST and then walks through the tree to extract:
- Tag names - All HTML elements (e.g.,
div,span,button) - Classes - Values from
classattributes, split by spaces - IDs - Values from
idattributes - Attributes - Both attribute names and values, useful for attribute selectors like
[data-theme]or[class*=foo]
MIT License