Tailwind && Laravel Mix - Getting that CSS filesize down
I wrote this on Saturday, April 4, 2020
I use the CSS utility library called Tailwind for a lot of sites these days - but as it generates thousands of classes that help you when you are building quickly - CSS filesizes can get BIG very quickly! Here is how I use Laravel Mix to get my filesizes down.
Let us start by compiling my assets with no optimisations:
2.19MB. That is up to two full seconds of just downloading the CSS for the site if you're on a poor 3G connection. Not good. Let's get that down.
Now, as we mentioned above, Tailwind generates thousands of classes allowing you to change singular CSS properties on the flow. Instead of changing CSS rules and re-compiling it, you manage the CSS classes inside your HTML - which is SO much faster, and much easier to grok what is going on with your styles as you can glance at the HTML to find out how something is put together.
When you are making your site, you are only going to use a small amount of these utility classes. You are not going to using all 93 colours with their hover:, focus:, active: varients - which adds around 400kb to the filesize by themselves! So is there a way we can look over our source code, find the classes we use and then extract the ones we don't?
Yes. Its called PurgeCSS.
Are you using Tailwind version 1.4.5 or later? PurgeCSS is now in-built into Tailwind. Read more on the Tailwind documentation page called Controlling File Size
Taken from the purge CSS docs: PurgeCSS analyzes your content and your CSS files. Then it matches the selectors used in your files with the one in your content files. It removes unused selectors from your CSS, resulting in smaller CSS files.
The clever folks at the powerhouse Spatie have come up with a plugin that makes PurgeCSS talk nicely with Laravel Mix - laravel-mix-purgecss
Please note - I recommend using the 4.2.0 version as I kept having issues with file read errors when compiling. Install by using the command:
$ npm install email@example.com
Integration with your site is easy. As far as the docs suggest its a config-less deployment inside a Laravel codebase, but as we are not using a Laravel codebase, we have a few options to edit before we are ready. My
webpack.mix.js is as below.
Let us run
npm run prod and generate my assets now:
Wow, an 98.9231% decrease down to 18.2kb file. Much better for the site speed 👀
The posts below have been selected based on the post you've just read!