Cara menggunakan detect unused css classes

How to remove unused CSS to reduce your app’s bundle size and maintain a clear and simple code.

Image by Ron Porter from Pixabay

CSS files can easily gain redundant KBs over time. It may happen due to leftovers from historic stylings or simply because you’ve used a large CSS framework like Bootstrap (147 KB when minimized) and most probably have used only a fraction of what it has to offer. Unused CSS slows down page loading and makes maintenance much more difficult than it has to.

Unused CSS in shared reusable UI components

Removing unused CSS is especially useful when sharing reusable UI components from your project, using Bit (Github).

Example: shared React components in bit.dev

For example, let’s say I have a simple React app with a header (‘Search’) and a search-bar component.

Both the header and the search-bar component require the same global CSS. When exporting my search-bar component to a Bit collection, Bit will identify that file as a dependency.

$ bit add src/components/*

and then, let’s try to tag all tracked components

$ bit tag --all

Bit returns an error — the component is dependant on a global CSS file:

I then add the CSS file:

$ bit add src/style.css

Let’s export the component with its CSS to my ‘unused-css-example’ collection:

$ bit export eden.unused-css-example

My search-bar component is now in my ‘unused-css-example’ collection:

The snapshot above tells us the style.css file was added to the collection as well. It is now a dependency of the search-bar. Whenever we npm install it or bit import it to a new project,we will get additional styling that has nothing to do with our search-bar component.

Hopefully you’re convinced by now :)

Let’s get on with the list:

1. PurgeCss

This is a tool that is very effective in cleaning out unused css styles.

The cool thing with purgecss is that it can be integrated into your development workflow. PurgeCSS can be used as a CLI tool from the terminal. Install it globally:

npm i purgecss -g

Run the following command in the terminal:

purgecss --css index.css --content index.html

The above will collect the index.css (as indicated by the — css flag) and index.html (as pointed to by the — content flag) and remove all unused CSS selectors in them.

It is available in NPM registry, and can be installed like this:

npm i purgecss -D

See it is installed as a development dependency, so it doesn’t follow you when pushing into production.

We create a JS file and pour in the following code:

// purgecss.jsvar Purgecss = require('purgecss') // ES5
import Purgecss from 'purgecss' // ES6
var purgecss = new Purgecss({
content: ['**/*.html'],
css: ['**/*.css']
})
var purgecssResult = purgecss.purge()

The content and css in the object passed to new Purgecss(...) contains glob pattern that tells PurgeCSS to collect the .html and .css files in the project and purge them of unused CSS code.

The purge method is called and the purgecssResult contains the result of the cleaned css.

We run the file using the node executable:

node purgecss.js

More on the Github repository:

2. PurifyCSS

This is another awesome tool, just like purgecss. PurifyCSS works by grabbing all HTML files specified for process comparison against any given CSS file. It searches through the HTML files and the given CSS files, it removes redundant CSS styles and writes the purified CSS to another file, then re-links the HTML files to the purified CSS file.

According to the authors:

A function that takes content (HTML/JS/PHP/etc) and CSS, and returns only the used CSS. PurifyCSS does not modify the original CSS files. You can write to a new file, like minification. If your application is using a CSS framework, this is especially useful as many selectors are often unused.

Its usage is super easy:

npm i purify-css -D

Next, create a file (I’ll call mine purify.js) and add the following code:

// purify.jsconst purify = require("purify-css")const htmlFiles = ['*.html'];
const cssFiles = ['*.css'];
const opts = {
output: 'purified.css'
};
purify(htmlFiles, cssFiles, opts, function (res) {
log(res);
});

We extracted the purify function from the package “purify-css”.

We then set the html files and css files that we want to clean of unused styles to htmlFiles and cssFiles respectively. They hold the files in an array. Here, we used the glob pattern to tell purify-css to collect all the .html and .css files in our project and purge them.

We set the configuration in opts. We just set the file path and name of where the purified css will be stored. There are many configurations we can set, like to minify the purified css, to display how much of unused CSS were purged.

Next, we call the purify function passing the htmlFiles, cssFiles, opts and a callback function that will be called with the result of the purification when it’s completed.

So we just run the purify.js to clean out all the unused css we have:

node purify.js

Check out the Github repository :

3. uncss

This is also a Node module that of course :) removes unused css. Just like we did with purifyCSS, it has a JS API that we call with options to removes unused css styles.

According to the author:

UnCSS is a tool that removes unused CSS from your stylesheets. It works across multiple files and supports Javascript-injected CSS.

We can install it as a global module and use it from the terminal:

npm i uncss -g

and use it from anywhere in our system.

A basic command-line usage of the uncss is this:

uncss src/app/app.component.html >> usedcss.css

All the used css in src/app/app.component.html will be written to usedcss.css.

JS usage is also simple:

// uncss.jsconst uncss = require("uncss")const htmlFiles = ["./index.html"]const opts = {
csspath: "styles/",
stylesheets: ["themes.css"]
}
uncss(htmlFiles, opts, (err, res) => {
if(err)
console.error(err)
console.log(res)
})

The function uncss is extracted from the “uncss” library. We place the html Files in an array, htmlFiles. The configurations are set in the opts. Lastly, the uncss is called with the htmlFiles, opts, and a callback function with a parameter that holds the error and another that holds the result.

The uncss.js file can then be run:

node uncss.js

See more the Github repository:

4. Coverage Tab in Chrome DevTools (Manually)

This Coverage tab helps us find unused Js and CSS code.

Open your Chrome browser, go to “Developer Tools”, click on “More Tools” and then “Coverage”.

A Coverage will open up. We will see buttons for start capturing coverage, to reload and start capturing coverage and to stop capturing coverage and show results.

If you have a webpage you want to analyze its code coverage. Load the webpage and click on the o button in the Coverage tab.

After sometime, a table will show up in the tab with the resources it analyzed, and how much code is used in the webpage. All the files linked in the webpage (css, js) will be listed in the Coverage tab. Clicking on any resource there will open that resource in the Sources panel with a breakdown of Total Bytes and Unused Bytes.

With this breakdown, we can see how many unused bytes are in our CSS files, so we can manually remove them or employ any of the tools we described above.

For more on this, see:

Conclusion

There goes the list of tools we can use to remove redundant and unused CSS code from our web apps.

So, check out your web apps to know whether you have useless codes in your codebase, and use the tools we just described to purge them. Remember, removing unused code can speed up your page load, and save your mobile users that precious cellular data.

Do you have any addition to the list, or why some shouldn’t be there, or you have a problem with one, or just wanna talk? Feel free to drop in your comments, or just can just mail or DM me.

Learn More