Skip to content

Instantly share code, notes, and snippets.

@50kudos
Last active November 3, 2019 02:03
Show Gist options
  • Save 50kudos/3028fac585eda85aea9a to your computer and use it in GitHub Desktop.
Save 50kudos/3028fac585eda85aea9a to your computer and use it in GitHub Desktop.
A Bash script that lists all unused css classes in html/haml/erb files for rails project (or maybe others depending on project structure)
#!/bin/bash
cat $(find app/assets/stylesheets/ -type f) |
grep -Eo '\.[a-z]+[a-z0-9_-]*' | sort | uniq | sed s/.// |
while read CSS; do
if ! grep -Erqi "([^(remove|has)]?class[(:|=|[:space:]*=>[:space:]*)]*[[:space:]\W]*[(\"|')]*[-a-z0-9[:space:]]*$CSS|\\.$CSS\b)" app/views/ vendor/assets/ app/assets/javascripts/; then
echo $CSS >> unused.scss;
fi
done
@50kudos
Copy link
Author

50kudos commented Jun 8, 2015

The script basically does:

  1. cat all css/scss classes files into one place
  2. Use every single css class to search in html (or haml, erb), vendor css and javascripts to see if this css is used.
  • html matched examples (css-class0), support normal html, old and new ruby hash class style:
html: {class: 'css-class0 class1'}
html: {:class => 'css-class0 class1'}
opts.merge(class: 'class1 btn css-class0'))
{ class: "#{'btn css-class0 class1' if @accounts.empty?}" }
class="class1 css-class0"
  • javascript: (css-class0)
$('.follower').addClass('css-class0');
$modal.append($('<div class="css-class0"></div>'));
  • vendor css: also search in vendor css in case that the css class is an overriding of vendor's css class
  1. If every single css class that's not found in those files by REGEX matching, it implies that the css class is not used and then write it to unused.css files.
  2. Final step should be manual. It's safe to use those unused css list to search in css files and remove its block by hand. I believe this step can't be done by bot, human decision is safer. Because for example:
  • css class can be pre-define and use in future e.g. typography set

@eakmotion
Copy link

👍

@julianvargasalvarez
Copy link

Thanks, very useful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment