PurgeCSS is not the only tool to remove unused CSS. Below you will find a comparison between PurgeCSS and the other two most used tools to remove unused CSS.
As indicated in its README, UnCSS works in the following way:
- PostCSS parses all the stylesheets. document.querySelector filters out selectors that are not found in the HTML files.
- The remaining rules are converted back to CSS.
However, its emulation can have a cost in terms of performance and practicality. To remove unused CSS from Pug template files, for example, you would need to convert Pug to HTML and emulate the page inside jsdom. After this step, UnCSS can run document.querySelector on each selector and perform Step 4.
PurifyCSS works by looking at all of the words in your files and comparing them with the selectors in your CSS. Every word is considered a selector, which means that a lot of selectors can be erroneously find used. For example, you may happen to have a word in a paragraph that matches a selector in your CSS.
PurgeCSS fixes this problem by providing the possibility to create an extractor. An extractor is a function that takes the content of a file and extracts the list of CSS selectors used in it. It allows a perfect removal of unused CSS.
The extractor can be used as a parser that returns an AST (abstract syntax tree) and looks through it to find any CSS selectors. This is the way purge-from-html works.
You can specify which extractors you want to use for each file type, allowing you to get the most accurate results. But using specific extractors is optional, and you can rely on the default one.