How do you get rid of unused CSS code? Part 2

Today we publish the second part of the translation of material on combating unused CSS code.







β†’ The first part



CSS postprocessing



Suppose in some project CSS is written using Less or Sass, and then, to compile the existing code into regular CSS, a post processor is used. In such a project, probably, there is an automatic system for getting rid of unused CSS, which starts after CSS preprocessing. This may look like this:



  1. Sass.
  2. PostCSS / automatic prefix system.
  3. Removing unused CSS.
  4. CSS code ready for production.


This, on the one hand, makes sense, and on the other - it looks a little strange in my eyes. The point is that with this approach, the source code containing stylization commands is not corrected, on the basis of which the resulting CSS code is created, which includes unused CSS. Instead, unnecessary CSS is simply removed at the end of the build process. I suspect that in JavaScript, when implementing the tree-shaking algorithm, something similar has been done for quite some time. That is, such handling with CSS is not news at all. But to me, this all the same seems to be wrong, since the CSS code base is something that can be said to lie on the surface of web projects. Such an approach almost prompts developers to carelessly write CSS, to get everything into the CSS source code. And the truth is that the system will get rid of unnecessary CSS automatically. But this completely deprives developers of the desire to understand exactly how their designs are styled, how exactly CSS is used in them.



Purgecss



PurgeCSS is another project that aims to combat unused CSS. Although this does not directly relate to the capabilities of this project, I like it because its documentation clearly explains its differences from competitors. Above, we have already given a fragment of a comparison between PurgeCSS and PurifyCSS. And here is another extract from PurgeCSS documentation dedicated to PurifyCSS. The point is that the main problem with PurifyCSS is the low modularity of this project. However, this is the main strength of PurifyCSS. As already mentioned, PurifyCSS considers CSS words to be all the words it finds in files. This approach is fraught with errors. But PurifyCSS solves this problem by making it possible to create extractor functions. Such a function takes the contents of a file and extracts from it a list of CSS selectors used in it. This allows you to very well solve the problem of getting rid of unused CSS code.



The PurgeCSS project now looks like a major player in the CSS code cleanup market. Many use it, many write about it.





Despite the fact that PurgeCSS needs special tuning to work with Tailwind, it seems that these two tools are perfectly combined with each other. In fact, even in the Tailwind documentation, you can find a recommendation for sharing them. And PurgeCSS has a command line tool for applying it in the process of building projects.



I think the essence of this comes down to the following: Tailwind creates a large CSS file full of helper selectors. But it is not assumed that all these selectors will be used in the project. The developer uses them to solve all the problems of styling his HTML-code, and then PurgeCSS analyzes this HTML-code and removes unnecessary selectors, forming CSS ready for production.



True, PurgeCSS still needs to be informed about each HTML and JavaScript file used on the site. In other words, you need to independently configure everything that relates to external resources, and take into account the fact that the data coming into the project from certain repositories is likely to not be analyzed during the assembly of the project. As a result, the use of PurgeCSS in the assembly of projects involves a considerable amount of manual work.



My favorite approach to getting rid of unused CSS



What I like most is the following approach to removing unnecessary CSS. It means that there would be someone in the project development team who is very familiar with the CSS code of this project. This person should be aware of current problems with styles and should gradually solve them. Perhaps this is an outdated view of the situation that belongs to a person who should keep up with the times. But to me, in any case, it seems the most practical approach. Considering that the task we are considering is so difficult to solve, I think that the answer to the challenge that this task poses to developers can be hard work. The answer is an understanding of the problem and its gradual solution. A front-end developer who is familiar with the project and knows what is used in it and what is not can solve this problem.



I saw one extreme approach to figuring out whether a site selector is used. The CSS block used a design like background-image: url(/is-this-being-used.gif?selector);



. After its application, server logs were periodically checked in order to find out whether a request was made to obtain the corresponding image. If there was such a request, then the CSS block under investigation is used. If it was not, then it is not used.



But perhaps my favorite tool in the unused CSS explorer toolkit is the one that will be discussed in the next section.



Study of projects by visual regression



This method consists in the fact that the developer takes as many screenshots of the site as possible. They make copies of the screens of the most important pages, and those pages, the appearance of which depends on the state of the application. Screenshots are taken in different browsers, with different screen sizes. These screenshots are created based on materials from the master



branch of the project repository.



Then, before merging any other branch with the master



branch, new screenshots are created based on the materials of the new branch and compared with those made for the master



branch. This, of course, is not done manually, but programmatically.



Strictly speaking, here is a video in which it is shown.



It should be noted that a lot has already been said on the topic of tools for studying visual regression, but the author of this video is the only person who explained everything extremely intelligibly. You need to not just take screenshots; you need to compare them and look for differences between them. One must not only find differences; you need to accept or reject them. In addition, it is necessary that the adoption or approval of changes would affect the process of merging branches in repositories. In addition, the developer should have the ability to configure the browser before taking a screen copy and the ability to automate the work with screenshots taken.



Atomic CSS and CSS-in-JS



I’m sure that many of the readers of this material can say: β€œI don’t have unused CSS, since the tools I use generate exactly the code I need and nothing more.”



If so, then this is just wonderful.



Perhaps we are talking about Atomizer . Perhaps this is the Tachyons tool, the results of which are passed through UnCSS and at the same time, are subject to increased caution. Maybe - this is a combination of Tailwind + PurgeCSS , which is now widely heard.



Maybe - they still work with styles somehow. If someone closely links JavaScript components and styles, say, as when using React and Emotion, or even just applies CSS modules with anything, among the advantages of such CSS-in-JS-approaches there is a reduction in the volume of unused CSS in finished projects. In addition, since many JavaScript-based projects use the tree-shaking algorithm and code separation techniques, such projects will not only have less unnecessary CSS. In the course of their work, only what is needed in each specific situation will be loaded. But, of course, there are drawbacks to such approaches to working with CSS.



Summary



Let's now think about how to avoid the appearance of unnecessary CSS code in our future projects. I believe that the future of styling is the separation between global styles and styles applied to individual components. Most styles are limited to the scope of components, but there are global styles that can be used to exploit the cascading nature of CSS. For example, it may be something like global standard typographic settings.



If most styles are limited by the scope of components, then I think that unnecessary styles are less likely to penetrate ready-made projects, since it is not difficult for a developer to delve into the relationship between small and closely related pieces of HTML and CSS. And when a component is removed from a project or developed, stylization leaves the project or develops with it. As a result, CSS assemblies are created based on the components actually used in the project.



CSS-in-JS technology is moving quite naturally in that direction. When applying such technologies, styles are tied to components. And this is the most important thing in this case. But binding styles to components is optional. I like the universal approach, which involves the use of CSS modules . It is almost completely aimed at separating the scope of styles and does not force the developer to use any specific JavaScript framework.



Maybe all of the above seems to you something theoretical or far from the real needs of web developers. You just have a site that uses Bootstrap, and would like to reduce the size of CSS that users of this site load. If so, I would advise you to use the Bootstrap source code rather than its standard build. This source code is written using SCSS and consists of many plug-ins. And this means that if you do not need some parts of Bootstrap, you can simply disable the corresponding modules.









Removing dropdowns, badges and breadcrumbs modules from Bootstrap before building a project



I wish you all good luck in the difficult struggle with unnecessary CSS code.



Dear readers! How do you deal with unused CSS code that gets into production?








All Articles