Have you ever wondered why your website loads slow sometimes? One reason could be large CSS files from libraries like Bootstrap. Today we’ll learn about a cool tool called PurgeCSS that can help speed up your website by removing unused CSS!
PurgeCSS is like a vacuum cleaner for your CSS. It scans your HTML and JavaScript files, checks which CSS rules you’ll actually use, and eliminates the ones you don’t need. This can make your CSS file much smaller, which helps your website load faster.
PurgeCSS works by analyzing your content files (HTML, JavaScript, etc.) and your CSS files, then removing unused CSS rules. Here's a step-by-step breakdown of the process:
If you have this CSS:
.btn { color: blue; }
.card { border: 1px solid gray; }
.unused-class { font-size: 20px; }
And this HTML:
<button class="btn">Click me</button>
PurgeCSS would output:
.btn { color: blue; }
The .card
and .unused-class
styles are removed because they're not used in the HTML.
This process can significantly reduce file size, especially when using large CSS frameworks where you often only use a small portion of the available styles.
To run PurgeCSS, we use the npx command. npx comes with Node.js, which must be pre-installed on your Ubuntu computer.
Before using PurgeCSS, you need to install it in your project. You can do this using either yarn or npm, which are popular package managers for JavaScript. Here are the commands to install PurgeCSS as a development dependency:
Using yarn:
$ yarn add purgecss --dev
Or if you prefer npm:
$ npm i -D purgecss
Here is a simple example of how to use PurgeCSS.
$ npx purgecss --css bootstrap.css --content index.html --output style.min.css
This tells PurgeCSS to:
You'll see that style.min.css is much smaller than bootstrap.css!
When using PurgeCSS, you can specify which files it should analyze to determine which CSS is being used. The --content parameter is flexible and can be adapted to different project structures and file types.
For Laravel Blade templates:
--content './resources/**/*.php'
This tells PurgeCSS to look at all PHP files (which include Blade templates) in the resources directory and its subdirectories.
For Ruby on Rails ERB templates:
--content './app/views/**/*.html.erb'
This instructs PurgeCSS to examine all ERB files in the views directory and its subdirectories.
You can also specify multiple content locations in a single command. For example:
$ npx purgecss --css bootstrap.css --content './index.html' './js/**/*.js' './components/**/*.vue' --output styles.min.css
This command tells PurgeCSS to:
By using multiple --content parameters, you can ensure PurgeCSS analyzes all relevant files in your project, regardless of where they're located or what type they are.