번들 크기 분석 및 축소
최종 CSS 출력 크기를 측정하고, 사용되지 않은 스타일이 포함되는 원인을 파악하며, 최대한 효율적으로 제거되도록 content 글로브 패턴을 조정합니다.
번들 크기 분석 및 축소은(는) CoddyKit의 무료 Tailwind CSS Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Tailwind CSS Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Tailwind CSS Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Bundle Size Still Matters With JIT
Tailwind's JIT engine eliminates most unused CSS automatically, but bundle size can still grow if you are not careful. An improperly configured content glob can include too many files, a large safelist can add hundreds of classes, or complex arbitrary values can inflate the output.
Even a well-configured Tailwind project benefits from occasional bundle auditing to confirm the output is as small as it should be and to catch configuration issues before they reach production.
Measuring Your CSS Output Size
The first step in analyzing your bundle is knowing its current size. Build your Tailwind CSS in production mode and check the file size before and after minification and compression.
Use wc -c to check raw bytes, and compare the gzip-compressed size which is what browsers actually download. A well-optimized Tailwind production stylesheet is typically 5-15KB uncompressed and 2-5KB gzipped.
# Build production CSS
NODE_ENV=production npx tailwindcss -i input.css -o dist/output.css --minify
# Check uncompressed size
wc -c dist/output.css
# Example output: 12048 dist/output.css (12KB uncompressed)
# Check gzipped size
gzip -c dist/output.css | wc -c
# Example output: 3421 (3.4KB gzipped — excellent)
# If size > 50KB uncompressed, investigate furtherChecking Content Glob Coverage
The most common cause of oversized Tailwind output is an overly broad content glob that scans too many files, including vendored libraries or generated output files that happen to contain CSS-class-like strings.
Accidentally including node_modules/** or your compiled output directory can cause JIT to generate thousands of spurious classes. Review each glob in your content array and ensure it only covers your actual source templates.
// BAD: Too broad — scans node_modules (thousands of spurious classes)
module.exports = {
content: ['**/*.{html,js}'], // matches ALL files including node_modules!
};
// GOOD: Scoped to your actual source directories
module.exports = {
content: [
'./src/**/*.{html,js,ts,tsx}',
'./pages/**/*.{js,ts,tsx}',
'./components/**/*.{js,ts,tsx}',
// Explicitly include specific external packages if needed:
'./node_modules/@headlessui/react/**/*.{js,ts}',
],
};Auditing With PurgeCSS Reports
You can use PurgeCSS in analyze mode (separate from Tailwind's built-in scanning) to generate a report of which CSS selectors are being kept and which would be removed. This helps identify unexpected classes in your output.
Alternatively, search your compiled CSS file for class patterns that should not be there: if you see hundreds of bg- variants including colors you never use, check your safelist patterns — they may be generating more classes than intended.
# Install PurgeCSS CLI
npm install -g purgecss
# Run PurgeCSS on your built CSS
purgecss --css dist/output.css \
--content './src/**/*.html' \
--output dist/purged.css \
--rejected-css dist/rejected.css
# Check rejected.css — classes in this file are in your built CSS
# but not found in your templates.
# If there are many, review your safelist and content configuration.Identifying Safelist Bloat
A large or broad safelist is a common source of bundle bloat. Each pattern generates many classes. For example, /bg-(red|green|blue|yellow|purple|orange|pink|indigo|violet|teal|cyan|rose)-(50|100|200|300|400|500|600|700|800|900|950)/ generates 132 background color classes alone — even if you only use 10 of them.
Audit your safelist by counting the patterns and estimating how many classes each generates. Remove patterns you added speculatively and only keep those for known dynamic class use cases.
// Bloated safelist (generates hundreds of classes)
safelist: [
{ pattern: /bg-(red|green|blue|yellow|purple|orange|pink)-(100|200|300|400|500|600|700|800|900)/ },
// ^ generates 63 classes
{ pattern: /text-(red|green|blue|yellow|purple|orange|pink)-(100|200|300|400|500|600|700|800|900)/ },
// ^ another 63
]
// Total: 126+ extra classes from safelist alone
// Optimized safelist (only what's actually used dynamically)
safelist: [
{ pattern: /bg-(red|green|yellow|blue)-(100|500)/ }, // 8 classes
{ pattern: /text-(red|green|yellow|blue)-(700|800)/ }, // 8 classes
]Removing Unused Base Styles
Tailwind's preflight (base CSS reset) adds approximately 4KB of base styles. If you are using Tailwind alongside a CSS framework that has its own reset, or if you are incrementally adopting Tailwind, you may want to disable preflight.
Set corePlugins: { preflight: false } in your config to remove the reset. This can save a few KB, especially in projects where the base styles conflict with existing CSS.
// tailwind.config.js — disable preflight
module.exports = {
corePlugins: {
preflight: false,
},
// OR: disable multiple core plugins to reduce output
corePlugins: {
preflight: false, // Remove reset styles
container: false, // Remove .container utility if unused
float: false, // Remove float utilities if not used
clear: false,
skew: false, // Remove skew transforms if not used
},
}Disabling Unused Core Plugins
You can disable entire groups of utilities that your project never uses to reduce the generated CSS. For example, a project with no CSS grid usage can disable the grid plugins. A project with no transforms can disable rotate, scale, skew, and translate.
Check your templates for utility prefixes you never use. Disabling a core plugin prevents all variants of those utilities from being generated, even if they somehow appear in the content scan (from template strings that resemble class names).
// tailwind.config.js
module.exports = {
corePlugins: [
// Whitelist approach: only enable plugins your project uses
// (Empty array = disable ALL core plugins — not recommended unless you know exactly what you need)
// Better: use the object form to disable specific ones
],
// Object form: disable only specific plugins
corePlugins: {
// If your project doesn't use blur/backdrop-filter at all:
backdropBlur: false,
backdropBrightness: false,
backdropContrast: false,
backdropGrayscale: false,
backdropHueRotate: false,
backdropInvert: false,
backdropOpacity: false,
backdropSaturate: false,
backdropSepia: false,
},
}Enabling CSS Compression
Beyond Tailwind's own minification (--minify), configure your build tool to apply additional CSS compression. Vite and webpack both support CSS minification via their built-in or plugin-based pipelines.
For maximum compression, combine CSS minification with Brotli compression on the server level. Brotli achieves 15-25% better compression than gzip on CSS files, reducing your effective payload further.
// vite.config.js — enable CSS minification
import { defineConfig } from 'vite';
export default defineConfig({
build: {
cssMinify: true, // default in production mode
cssCodeSplit: true, // split CSS per page in multi-page apps
},
});
// next.config.js — Next.js minifies CSS automatically in production
// No extra configuration neededTree-Shaking Unused JavaScript in Tailwind Projects
In React and Vue projects, tree-shaking eliminates unused JavaScript, but it also affects how classes reach JIT. If a component is tree-shaken from the bundle, its class strings might not appear in the compiled JS, causing JIT to miss them.
The solution is to configure your content globs to point to source files (pre-tree-shake), not compiled output. JIT should always scan your source TypeScript/JavaScript files, not the compiled bundle.
// tailwind.config.js
module.exports = {
content: [
// Source files (correct): JIT sees all possible classes
'./src/**/*.{ts,tsx}',
'./src/**/*.{js,jsx}',
// Compiled output (wrong): some classes may be missing
// './dist/**/*.js', // Don't scan compiled output
],
}Analyzing Bundle Size Over Time
Bundle size tends to grow gradually as features are added. Set up a CI check that measures CSS bundle size on every pull request and fails if it exceeds a threshold. This catches accidental safelist expansions or overly broad glob additions before they reach production.
Tools like bundlesize, size-limit, or a simple bash script comparing file sizes can integrate into your CI pipeline to enforce size budgets.
# .github/workflows/css-size-check.yml
# Build CSS and fail if it exceeds 20KB
npx tailwindcss -i input.css -o /tmp/tailwind.css --minify
CSS_SIZE=$(wc -c < /tmp/tailwind.css)
echo "CSS size: ${CSS_SIZE} bytes"
if [ ${CSS_SIZE} -gt 20480 ]; then
echo "ERROR: CSS bundle exceeds 20KB limit (${CSS_SIZE} bytes)"
exit 1
fiFinal Optimization Checklist
Before shipping a Tailwind project to production, run through this checklist:
NODE_ENV=productionis set during the build- Content globs do not include
node_modulesbroadly - Safelist patterns are narrow and documented
- Unused core plugins are disabled in config
- CSS is minified (Tailwind
--minifyflag or build tool) - Server compression (gzip or Brotli) is enabled
- CSS file size is under your target budget (typically 15KB uncompressed)
# Full production optimization command
NODE_ENV=production npx tailwindcss \
-i ./src/input.css \
-o ./dist/tailwind.min.css \
--minify
# Verify result
echo 'Uncompressed:' $(wc -c < ./dist/tailwind.min.css) 'bytes'
echo 'Gzipped:' $(gzip -c ./dist/tailwind.min.css | wc -c) 'bytes'Quick Check
Test your understanding of Tailwind CSS Mastery concepts from this lesson.
Lesson Recap
In this lesson you learned: CSS bundle size measurement using the production build with --minify and wc -c plus gzip inspection; content glob scoping to prevent JIT from scanning node_modules or output directories; and safelist auditing to ensure patterns are narrow and only cover genuinely dynamic class use cases. Next up we explore arbitrary values and their cost.
자주 묻는 질문
“번들 크기 분석 및 축소” 강의는 무료인가요?
네 — “번들 크기 분석 및 축소” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Tailwind CSS Academy 강의 전체를 잠금 해제할 수 있습니다. Tailwind CSS Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“번들 크기 분석 및 축소”에서 뭘 배우나요?
최종 CSS 출력 크기를 측정하고, 사용되지 않은 스타일이 포함되는 원인을 파악하며, 최대한 효율적으로 제거되도록 content 글로브 패턴을 조정합니다. 브라우저에서 직접 실행하는 실습 코드로 Tailwind CSS Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Tailwind CSS Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Tailwind CSS Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“번들 크기 분석 및 축소” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Tailwind CSS Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Tailwind CSS Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- JIT 엔진의 작동 방식
- 동적 클래스 안전 목록 관리
- 번들 크기 분석 및 축소
- 임의 값과 그 비용