SmartCodingTips

Purging Unused CSS for Production

Tailwind generates thousands of utility classes, which can make your final CSS file large. To optimize for production, you should remove unused styles using Tailwind’s built-in **PurgeCSS** (now integrated with Tailwind itself).

1. Why Should You Purge?

  • Reduces file size drastically
  • Improves website loading speed
  • Better SEO and performance metrics

2. How to Enable Purge in Tailwind

In your tailwind.config.js file, set the `content` option like this:


module.exports = {
  content: [
    './*.html',
    './src/**/*.{js,ts,jsx,tsx}',
    './components/**/*.php',
  ],
  theme: {
    extend: {},
  },
  plugins: [],
};
            

This tells Tailwind to scan only those files for used class names.

3. Build CSS for Production

Use the Tailwind CLI or your build tool (PostCSS, Laravel Mix, Vite, etc.):


npx tailwindcss -o build.css --minify
            

The --minify flag ensures the CSS is purged and compressed.

4. Tips for Best Results

  • Use actual class names, not dynamic strings.
  • Avoid building classes via JS (like "text-" + color).
  • If needed, use safelist in the config for dynamic classes.

5. Safelisting Classes

Add dynamic or conditionally-used classes manually like this:


module.exports = {
  content: [...],
  safelist: [
    'text-red-500',
    'bg-green-100',
    /^bg-(red|green|blue)-(100|200|300)$/,
  ],
};
            

Conclusion

With Tailwind’s purge capabilities, you can safely use all the utility classes you need during development and enjoy a lean, performant CSS bundle in production.