Skip to main content
🏠Getting StartedOptimization for productionVersion: 2.0.0-beta.6

Optimization for production

About PurgeCSS

PurgeCSS is a tool to remove unused CSS. It can be part of your development workflow. When you are building a website, you might decide to use a CSS framework like Thales Design System. But you will only use a small set of the framework, and a lot of unused CSS styles will be included.

This is where PurgeCSS comes into play. PurgeCSS analyzes your content and your CSS files. Then it matches the selectors used in your files with the one in your content files. It removes unused selectors from your CSS, resulting in smaller CSS files.

Writing purgeable HTML

Before getting started with the purge, it’s important to understand how it works and build the correct mental model to make sure you never accidentally remove important styles when building for production.

PurgeCSS is intentionally very naive in the way it looks for classes in your HTML. It doesn’t try to parse your HTML and look for class attributes or dynamically execute your JavaScript — it simply looks for any strings in the entire file that match this regular expression:

/[^<>"'`\s]*[^<>"'`\s:]/g

This basically matches any string separated by spaces, quotes or angle brackets, including HTML tags, attributes, classes, and even the actual written content in your markup.

That means that it is important to avoid dynamically creating class strings in your templates with string concatenation, otherwise PurgeCSS won’t know to preserve those classes.

Don't use string concatenation to create class names

  <div class="text-{{  error  ?  'red'  :  'green'  }}-600"></div>

Do dynamically select a complete class name

  <div class="{{  error  ?  'text-red-600'  :  'text-green-600'  }}"></div>

PurgeCSS installation

Check PurgeCSS documentation for using it with different front-end frameworks and different module bundlers.