Tailwind CSS Performance: Purging, JIT, and Bundle Size
Tailwind generates thousands of utility classes by default. Without optimization, your CSS bundle is huge. With JIT and purging, it's typically under 10KB.
How Tailwind Optimizes
Tailwind v3+ uses JIT (Just-In-Time) mode by default. It scans your source files, finds every class you use, and generates only those classes.
Result: production CSS is typically 5-15KB instead of 3MB.
Configuration
// tailwind.config.ts
import type { Config } from 'tailwindcss';
export default {
content: [
'./app/**/*.{js,ts,jsx,tsx,mdx}',
'./components/**/*.{js,ts,jsx,tsx,mdx}',
'./lib/**/*.{js,ts,jsx,tsx}',
],
// ^^ Critical: Tailwind scans these files for class names
theme: { extend: {} },
plugins: [],
} satisfies Config;
Dynamic Classes (The Gotcha)
// BROKEN: Tailwind can't detect dynamically constructed class names
const color = 'red';
<div className={`text-${color}-500`} />
// Tailwind sees 'text-${color}-500' — not 'text-red-500'
// Class never generated, no styles applied
// CORRECT: Use complete class names
const colorClasses = {
red: 'text-red-500 bg-red-100',
blue: 'text-blue-500 bg-blue-100',
green: 'text-green-500 bg-green-100',
} as const;
<div className={colorClasses[color]} />
Safelist (Force-Include Classes)
// tailwind.config.ts
export default {
safelist: [
'text-red-500',
'text-blue-500',
// Or patterns:
{ pattern: /bg-(red|blue|green)-(100|500)/ },
],
};
Custom Utilities
// Add custom utilities that participate in JIT
import plugin from 'tailwindcss/plugin';
export default {
plugins: [
plugin(({ addUtilities }) => {
addUtilities({
'.text-balance': { 'text-wrap': 'balance' },
'.no-scrollbar': {
'-ms-overflow-style': 'none',
'scrollbar-width': 'none',
'&::-webkit-scrollbar': { display: 'none' },
},
});
}),
],
};
Measuring Bundle Size
# Build and check output
npm run build
ls -lh .next/static/css/*.css
# Or use Next.js bundle analyzer
ANALYZE=true npm run build
Typography Plugin
npm install @tailwindcss/typography
plugins: [require('@tailwindcss/typography')]
<article class="prose prose-gray max-w-none">
<!-- Markdown rendered with beautiful typography -->
</article>
Useful Plugins
npm install @tailwindcss/forms # Better form styling
npm install @tailwindcss/typography # Prose styling for markdown
npm install @tailwindcss/container-queries # Container query utilities
npm install tailwind-merge # Merge conflicting classes safely
npm install clsx # Conditional class names
Tailwind ships pre-configured with shadcn/ui in the AI SaaS Starter Kit — typography plugin, forms plugin, and custom brand colors. $99 at whoffagents.com.
Top comments (0)