Similar to reducing build times by finding and removing unused packages from our
we can use bash to find other assets that are not used anywhere in our codebase and unnecessarily increase the repo size.
We're going to use the
find command to create a list of all the assets we want to iterate over and check if they are used in our codebase.
Of course, this can be done for multiple formats and files, either separately or in the same list and iteration. To keep it simple here,
we're going to create a temporary file with all images (png and jpg) and use the
grep command to check for any occurrences in our code.
The real lookup happens inside our loop, which iterates over all the images we collected with
find. We're giving
-Rq flags to make it recursive and quiet, so it doesn't return any errors to the console and then pipe the outcome to
|| pipe will only ever output the results of
echo when the left-hand statement throws an error, which in our case means
didn't find the pattern in any of the files it was looking through. Which also means, the image wasn't used anywhere in our code.
Just like using a script to optimize our assets, it can be very beneficial to have a re-usable bash script that can help us find unused CSS in our projects and works the same across all projects. Let's take a look at how we can achieve this with the tools we've already learned about.
First, we need to get a list of all CSS selectors that have been declared across our codebase. We can use
grep to go through
*.scss files, looking for the pattern
^\s*\., which equals CSS classes — strings starting with a dot. We'll first write them into a temporary file,
before using a few
sed operations to clean out the string, eg. remove curly braces, pseudo-selectors, dots, etc.
We're passing the flags
-hr to our initial
-hrq to the second
grep to prevent it from printing out filenames or errors and
to make sure it's recursively looking through all sub-folders inside
./src. Inside our loop, we include all
js files to check
for occurrences of the selectors in our list. Just like with finding images and assets above, we only print those CSS selectors that
grep can't find in our codebase, leading us to a list of all unused selectors.
Keep in mind that this is a very naive and simple approach that might not find all nested or complex selectors, especially when dealing with SASS and other preprocessors.form