PurgeCss is a node package that allows you to strip out all the unnecessary CSS code from your compiled files.
This package reads your CSS files and removes all the useless styles based on the selectors from your HTML views.
See the following basic implementation taken from the official documentation:
The pitfall
If you generate some CSS tags from your backend based on any response, you won’t get the expected output at the end of the process.
Let’s see the following example using PHP
In this example, $type
could return maybe “success” or “error” so at the end you’ll end up with alert-error
or alert-success.
As PurgeCss doesn’t recognize the actual value of the variable, and the final CSS selector, is going to remove any style that you have defined for that selector:
The output after using PurgeCss would be the following:
.alert { color: white; }
Whitelisting selectors
The good news is that PurgeCss allows specifying a list of selector you want to keep, even though if they aren’t present in your HTML files
Even better! You can use a regular expression to keep any selector that matches the given pattern, for instance:
There is a third option that I don’t really like that much, which is adding a comment in your CSS above any selector to prevent PurgeCss from removing it:
As I said before, I’m not a big fan of this approach, but you can use the one you like the most, I won’t judge you for that.
https://gfycat.com/actualplainamazonparrot
Bonus
If you use Laravel-mix, you can use the laravel-mix-purcss package developed by the spatie.be team, to add a purgeCss()
method to your “mix” pipeline:
The mix.purgeCss()
method receives the same configuration object supported by the original purgeCss package, see Configuration - Purgecss
And in case you are wondering... Yes, you can use laravel-mix
outside the Laravel framework, take a look at the docs here: https://github.com/JeffreyWay/laravel-mix
Wrapping up
PurgeCss is a powerful tool that allows you to keep your CSS files at the minimum, and with the right configuration, you can make your development process more flexible.
Resources
- Laravel Mix: https://laravel.com/docs/5.8/mix
- Laravel Mix PurgeCss: https://github.com/spatie/laravel-mix-purgecss
- PurgeCss docs: https://www.purgecss.com/configuration