동적 클래스 안전 목록 관리
tailwind.config.js의 safelist 옵션을 사용하여 JIT가 정적으로 감지할 수 없는 동적 구성 클래스 이름이 항상 포함되도록 합니다.
동적 클래스 안전 목록 관리은(는) CoddyKit의 무료 Tailwind CSS Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Tailwind CSS Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Tailwind CSS Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
The Safe-Listing Problem
JIT's static scan is a strength for most cases, but it creates a challenge when class names are determined at runtime — from a database, an API response, or a user's color preferences. These dynamically determined class names never appear as complete strings in your source files, so JIT does not generate them.
The safelist in tailwind.config.js is the official solution: you explicitly list classes (or patterns) that JIT must always generate, regardless of whether they appear in your template files.
Basic Safelist Configuration
Add a safelist array to your tailwind.config.js. List any complete class names that JIT cannot detect statically. JIT will always generate CSS for every class in this array, even if it does not find them in your content files.
This is the simplest form of safe-listing — individual class names. It works well for a small number of known dynamic classes.
// tailwind.config.js
module.exports = {
content: ['./src/**/*.{html,js,ts}'],
safelist: [
'bg-red-500',
'bg-green-500',
'bg-blue-500',
'bg-yellow-500',
'text-white',
'text-gray-900',
],
theme: {
extend: {},
},
plugins: [],
}Pattern-Based Safelisting
For dynamic values across an entire color scale, listing every individual class is tedious. Instead, use a pattern object in the safelist that specifies a regex pattern. JIT will generate all classes matching the pattern.
For example, to generate all background colors for alert levels (red, green, yellow, blue) across shades 100 and 700, you can use a pattern that matches exactly those combinations.
// tailwind.config.js
module.exports = {
content: ['./src/**/*.{html,js}'],
safelist: [
// Generate all bg-* text-* combinations for status colors
{
pattern: /bg-(red|green|blue|yellow|purple)-(100|500|700)/,
},
{
pattern: /text-(red|green|blue|yellow|purple)-(700|800|900)/,
},
{
pattern: /border-(red|green|blue|yellow|purple)-(300|500)/,
},
],
theme: {
extend: {},
},
}Generating Variants With Patterns
Pattern-based safelisting also supports generating variants alongside the base class. Add a variants array to the pattern object to include hover, focus, dark, and responsive variants.
This is essential when the dynamically determined class is used inside interactive elements. For example, a status badge that changes color based on a database field needs its hover state generated too if the badge is a clickable button.
// tailwind.config.js
module.exports = {
safelist: [
{
pattern: /bg-(red|green|blue|yellow)-(100|200|500|600)/,
variants: ['hover', 'focus', 'dark', 'dark:hover'],
},
{
pattern: /text-(red|green|blue|yellow)-(600|700|800)/,
variants: ['hover', 'dark'],
},
],
}When to Use Safelisting
The safelist should be a last resort, not a first instinct. Before safe-listing, consider these alternatives:
- Map values to full class strings in a JavaScript object — the cleanest solution
- Inline styles for truly arbitrary runtime values like user-chosen hex colors
- CSS variables with a fixed Tailwind class that references the variable
Overusing the safelist defeats the purpose of JIT and can re-introduce the problem of large CSS files.
// Preferred: map values to complete class strings
const statusClasses = {
success: 'bg-green-100 text-green-800 border-green-300',
error: 'bg-red-100 text-red-800 border-red-300',
warning: 'bg-yellow-100 text-yellow-800 border-yellow-300',
info: 'bg-blue-100 text-blue-800 border-blue-300',
};
// Usage in template:
// class={statusClasses[status]}
// JIT detects all four strings statically — no safelist needed!Inline Styles for Truly Dynamic Values
When a value is truly arbitrary at runtime — like a user's custom brand color stored in a database — inline styles are the right tool. Tailwind utilities map to fixed values on the design scale, while inline styles can accept any computed value.
Combine Tailwind for layout and structure with inline styles for the one truly dynamic value. This keeps 99% of your styling in Tailwind and reserves inline styles for the specific dynamic case.
<!-- User's custom brand color from database -->
<div
class="px-6 py-4 rounded-xl font-semibold text-white"
style="background-color: {{ user.brandColor }}">
Custom Brand Header
</div>
<!-- The layout, padding, rounding, and text color all use Tailwind utilities -->
<!-- Only the dynamic database value uses inline style -->
<!-- This keeps the JIT stylesheet small and Tailwind responsible for design scale -->
<!-- CSS variable approach (also good):
<style> :root { --brand: {{ user.brandColor }}; } </style>
<div class="bg-[var(--brand)] px-6 py-4 rounded-xl text-white">...</div>
-->CSS Variables as Dynamic Values
A powerful technique is to set a CSS variable to the dynamic value and reference it with Tailwind's arbitrary value syntax: bg-[var(--brand-color)]. The class string bg-[var(--brand-color)] is a complete static string that JIT can detect and generate.
The CSS variable itself is then updated dynamically via JavaScript or inline styles on a parent element, while the class stays fixed in your template.
<!-- Static class referencing a CSS variable -->
<div
id="card"
class="bg-[var(--card-bg)] text-[var(--card-text)] px-6 py-4 rounded-xl">
Dynamically colored card
</div>
<script>
// Update the CSS variable dynamically
const card = document.getElementById('card');
card.style.setProperty('--card-bg', '#1a1a2e');
card.style.setProperty('--card-text', '#e0e0e0');
// The class 'bg-[var(--card-bg)]' is a static string
// JIT generates it because it appears literally in the HTML
</script>Safelist in a Monorepo or Component Library
When building a component library that other projects will consume, classes in your library's components must be included in the consuming project's JIT scan. Include the library's source in the content array of the consumer's config, or use a preset that ships a safelist.
If the library ships compiled JavaScript (not source HTML), add the package path to the consumer's content glob, pointing to the compiled JS files that still contain the class strings as literal strings.
// Consumer project's tailwind.config.js
module.exports = {
content: [
'./src/**/*.{html,js,ts,tsx}',
// Include the UI library's compiled files so JIT finds its classes
'./node_modules/@my-company/ui/**/*.{js,ts}',
],
safelist: [
// Or explicitly list classes the library uses dynamically
{
pattern: /bg-(blue|red|green|gray)-(50|100|500|600|700)/,
},
],
}Verifying the Safelist Works
After adding classes to the safelist, verify they are being generated by inspecting the compiled CSS output. Run npx tailwindcss -i input.css -o output.css and search the output file for one of the safelisted classes.
If the class is missing, double-check the regex pattern in the safelist (regex errors are silent). You can also temporarily add the class as a string to the safelist to confirm the configuration is being read at all.
# Build and verify
npx tailwindcss -i input.css -o output.css
# Check if safelisted class is in output:
grep 'bg-red-500' output.css
# Should print: .bg-red-500 { background-color: #ef4444; }
# If missing, test with direct string:
# safelist: ['bg-red-500'] -- if this works, your regex is wrong
# Regex debugging:
const pattern = /bg-(red|green)-(100|500)/;
console.log(pattern.test('bg-red-500')); // true
console.log(pattern.test('bg-red-600')); // false -- 600 not in patternBlocklist to Exclude Classes
The opposite of a safelist is a blocklist — classes you want to prevent from being generated even if JIT detects them in your templates. This is rarely needed but useful when you are overriding Tailwind classes with custom CSS and want to avoid specificity conflicts from the generated utilities.
Add a blocklist array to tailwind.config.js with class names to exclude. JIT will skip these even if found in content files.
// tailwind.config.js
module.exports = {
content: ['./src/**/*.{html,js}'],
blocklist: [
// Prevent these classes from being generated
// (e.g., you have custom .container styles that conflict)
'container',
// Prevent a whole pattern:
// blocklist does NOT support regex -- individual names only
],
theme: {
extend: {},
},
}Safelisting From External Data Sources
In headless CMS projects, blog platforms, or user-themeable apps, class names may come from a database or CMS content field. The safelist should cover the set of all possible values the CMS allows users to choose from.
Document the allowed class set, restrict CMS inputs to that set, and mirror the restriction in the safelist pattern. This ensures no class is used in content that is not generated in the stylesheet — a common bug in CMS-driven Tailwind projects.
// Allowed alert colors in your CMS:
// success, error, warning, info
// Tailwind classes for each stored in CMS: 'bg-green-100', 'bg-red-100', etc.
// tailwind.config.js safelist:
module.exports = {
safelist: [
// Exact list matching what CMS allows
'bg-green-100', 'text-green-800', 'border-green-300',
'bg-red-100', 'text-red-800', 'border-red-300',
'bg-yellow-100', 'text-yellow-800', 'border-yellow-300',
'bg-blue-100', 'text-blue-800', 'border-blue-300',
],
}Quick Check
Test your understanding of Tailwind CSS Mastery concepts from this lesson.
Lesson Recap
In this lesson you learned: the safelist in tailwind.config.js forces JIT to generate classes regardless of whether they appear in scanned content files; pattern objects with regex values generate entire sets of related classes efficiently; and the best alternatives to safelisting are mapping dynamic values to complete class strings in JS objects, using inline styles for truly arbitrary runtime values, or leveraging CSS variables referenced with Tailwind's arbitrary value syntax. Next up we analyze and reduce bundle size.
자주 묻는 질문
“동적 클래스 안전 목록 관리” 강의는 무료인가요?
네 — “동적 클래스 안전 목록 관리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Tailwind CSS Academy 강의 전체를 잠금 해제할 수 있습니다. Tailwind CSS Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“동적 클래스 안전 목록 관리”에서 뭘 배우나요?
tailwind.config.js의 safelist 옵션을 사용하여 JIT가 정적으로 감지할 수 없는 동적 구성 클래스 이름이 항상 포함되도록 합니다. 브라우저에서 직접 실행하는 실습 코드로 Tailwind CSS Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Tailwind CSS Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Tailwind CSS Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“동적 클래스 안전 목록 관리” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Tailwind CSS Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Tailwind CSS Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- JIT 엔진의 작동 방식
- 동적 클래스 안전 목록 관리
- 번들 크기 분석 및 축소
- 임의 값과 그 비용