Easily Refactored CSS
I quickly detected and organized "unused CSS" that tends to accumulate in personal development websites using a Node.js script.
Hello! I'm PanKUN.
As I repeated adding features and changing designs, classes like "Where is this used again?" started to increase in my CSS files.
- A button class written for Design Plan A, but eventually Plan B was adopted so it became unused.
- A style created to be common, but ended up being left alone because a specific class was used.
And so on. It works even if left alone, but it wastes file size and above all, it's not good for mental health.
So, I decided to refactor these this time.
Searching manually is impossible
However, searching for class names written in CSS files one by one to confirm "zero usage" is an ordeal.
There are convenient tools like PurgeCSS in the world, but incorporating them into the build process can be a bit difficult or the settings can be complicated.
Since my motivation this time was "I want to delete unnecessary things more easily and roughly", I decided to write a simple script in Node.js to detect them.
Policy of the self-made script
- Read all CSS files in the
assets/css/folder. - Extract class names (
.classname) and ID names (#idname) using regular expressions. - Scan all files in the project (HTML, JS, MD, etc.).
- If "the extracted class name never appears in any file", output it as an unused candidate.
That's it. I don't do strict syntax analysis (AST) etc., but judge by simple string search (includes).
To that extent, there is a weakness that "detection will be missed if the same word as the class name happens to be in the text", but it is sufficient for the purpose of "safely deleting unused things".
// tools/find-unused-css.js (excerpt)
const cssContent = fs.readFileSync(cssFile, 'utf8');
const selectors = extractSelectors(cssContent); // Extract with regex
selectors.forEach(sel => {
let isUsed = false;
for (const content of contents) {
// Simple string search
if (content.includes(sel.name)) {
isUsed = true;
break;
}
}
if (!isUsed) {
console.log(`[UNUSED] ${sel.name}`);
}
});Execution Result
When I ran the script, I found several unused classes.
Checking assets\css\layout.css...
[UNUSED] .section--soft
Checking assets\css\top.css...
[UNUSED] .btn-outlineUpon checking,
section--soft was a variation of a card made in the initial design draft,
btn-outline was a button with only a border, and currently only filled buttons were used.
These are completely unnecessary, so delete them without hesitation! The CSS file has become a little slimmer.
Summary
Refactoring tends to be imagined as a large-scale task, but if you take the approach of "write a small script and check quickly if you are curious", it seems possible to keep the code clean on a daily basis.
It is a pleasure unique to engineers to improve their own site with tools made by their own hands.
Loading comments...