How to Leverage PurgeCSS in Your Rails App for Faster Stylesheets
It’s common for Rails applications to serve massive CSS files filled with unused Bootstrap, Tailwind, or custom utility classes as projects grow. This bloat isn’t just a developer annoyance—it has a real impact on your users. Every unused kilobyte adds milliseconds to page load time. In this post, we’ll explore what PurgeCSS is and how your Rails project can benefit from it.
What Is PurgeCSS and Why Should You Care?
PurgeCSS is a tool that analyzes your content and CSS, then removes unused CSS selectors, stripping away dead weight to leave you with lean, optimized stylesheets.
For example, if you’re using the full Bootstrap CSS framework (approximately 200KB) but only utilizing 30% of its components, PurgeCSS can scan your HTML (ERB files), JavaScript (including Stimulus controllers), and other templates to identify which Bootstrap classes you actually use. It then generates a new CSS file containing only those classes, potentially reducing your Bootstrap footprint by 70% or more.
Benefits for Your Rails Application
PurgeCSS improves performance by reducing the amount of data browsers must download, parse, and process—directly improving metrics like Largest Contentful Paint (LCP). Beyond faster load times, tools like Google PageSpeed Insights and Lighthouse reward lean assets, making unused CSS removal a high-impact, low-effort optimization.
This approach also enhances developer experience by allowing you to confidently use large CSS frameworks or generate extensive utility classes (like with Tailwind) without worrying about shipping bloated, unused code to production.
Implementing PurgeCSS in Rails
The cleanest way to integrate PurgeCSS into a Rails application is using the cssbundling-rails gem, the modern successor to Webpacker for CSS (with jsbundling-rails covering the JavaScript side). It seamlessly integrates PostCSS and other build processes into assets:precompile.
Prerequisites and Setup
First, ensure you’re using cssbundling-rails to build your CSS. If you created a new Rails app with rails new myapp --css=bootstrap, you’re already using it.
For older applications, you may need to migrate. This guide assumes you have a setup that uses yarn build:css to process your styles.
Installation
Since PurgeCSS is a PostCSS plugin, we’ll install it and add it to our PostCSS configuration. Add the package using Yarn:
yarn add -D @fullhuman/postcss-purgecss
Configuration
Next, open (or create) your postcss.config.js file in your Rails project root. It’s important to only run PurgeCSS in production since running it in development would strip classes with every file change, severely impacting developer experience.
To gate it, we check NODE_ENV rather than RAILS_ENV. PostCSS runs inside the Node process that cssbundling-rails spawns for yarn build:css, and RAILS_ENV isn’t reliably exported into that child process across every platform and CI setup. NODE_ENV is the signal the Node toolchain already understands, so make sure your production build sets NODE_ENV=production (Rails does this by default during assets:precompile).
Here’s a sample configuration:
// postcss.config.js
module.exports = {
plugins: [
require('postcss-import'),
require('postcss-nesting'),
require('autoprefixer'),
// Only run PurgeCSS in production
...(process.env.NODE_ENV === 'production' ? [
require('@fullhuman/postcss-purgecss')({
content: [
'./app/views/**/*.html.erb',
'./app/helpers/**/*.rb',
'./app/javascript/**/*.js',
'./app/javascript/**/*.ts',
'./app/components/**/*.rb',
'./app/components/**/*.html.erb',
// Add any other directories containing class names
],
defaultExtractor: content => content.match(/[A-Za-z0-9-_:/]+/g) || [],
safelist: [
/bg-(red|green|blue)-\d00/, // Dynamic class patterns (e.g., bg-red-500)
'btn-primary',
'is-invalid',
/^alert-/,
/^modal-/,
// Add classes added via JavaScript not found in static templates
]
})
] : [])
]
}
Configuration Breakdown
- content: This array tells PurgeCSS where to find CSS class names. We include ERB templates, helpers that generate HTML with classes, JavaScript files (including Stimulus controllers), and component directories.
- defaultExtractor: This function extracts class names from your files. The provided regex handles various class name formats, including those with colons (like
sm:flex). It’s a permissive starting point that errs toward keeping more tokens (it also matches/), so it’s safer than it is precise. If you’re on Tailwind, prefer Tailwind’s own extractor rather than rolling your own here. - safelist: Essential for preserving dynamically added classes. You can safelist specific strings (
'btn-primary') or use regular expressions (/bg-(red|green|blue)-\d00/for Tailwind color utilities).
Testing and Deployment
With configuration complete, build for production:
RAILS_ENV=production bundle exec rails assets:precompile
This runs your CSS build process with PurgeCSS enabled. Check the compiled CSS file in public/assets—you should see a dramatically smaller file compared to your development version.
Crucially, thoroughly test in a staging environment before deploying to production. Click through every page and application state to identify any missing styles. If you find issues, add the missing classes or patterns to your safelist array.
Important Considerations
- Stage Before Production: PurgeCSS can be aggressive. Test in a staging environment that mirrors production data, as some classes may only appear under specific conditions or with certain data.
- Use Safelist Liberally: When in doubt, add classes to your safelist. It’s better to preserve a few extra classes than to have broken styles.
- Tailwind Users: If you’re using Tailwind CSS (via the
tailwindcss-railsgem), you don’t need PurgeCSS at all. Tailwind dropped PurgeCSS back in v3 in favor of its JIT engine, which only ever generates the classes it finds in yourcontentpaths. Your job there is simply to keep thosecontentpaths intailwind.config.jscomprehensive so nothing you actually use gets missed.
Conclusion
Integrating PurgeCSS into your Rails asset pipeline is straightforward and offers substantial benefits. By systematically removing unused CSS, you deliver faster, more performant experiences to users while maintaining the developer-friendly workflow of comprehensive CSS frameworks.
Need Help Speeding Up Your Rails App?
If you’d like a hand trimming unused CSS, optimizing your asset pipeline, or improving your app’s performance, we’d be happy to help. Send us a message over here: FastRuby.io Contact Form