0Pricing
Tailwind CSS Academy · 课时

内容路径与清除未使用样式

正确配置 content 数组,确保 Tailwind 扫描所有文件,并在生产构建中移除未使用的 class。

内容路径与清除未使用样式 是 CoddyKit 上的免费 Tailwind CSS Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Tailwind CSS Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Tailwind CSS Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Purging Matters

Tailwind CSS generates utility classes for every combination of your theme values — potentially hundreds of thousands of classes. Without pruning, the raw CSS output would be several megabytes. The purging process (officially called content scanning or tree-shaking) removes every class that does not appear in your source files, shrinking the production CSS to typically just 5–50 KB. Getting your content configuration right is essential for a lean build.

How Content Scanning Works

Tailwind scans the files you list in the content array and searches for string patterns that look like Tailwind class names. It does not execute your code — it does a simple text search. Any string that matches a known utility class is included in the output. This is why you must never construct class names dynamically by concatenating strings; the scanner won't find the full class name.

// BAD: Tailwind cannot detect 'text-red-500'
const color = 'red';
const cls = 'text-' + color + '-500';  // scanner sees 'text-' + 'red' + '-500'

// GOOD: Full class names are always present in source
const cls = isError ? 'text-red-500' : 'text-green-500';  // scanner sees both

Writing Content Glob Patterns

Glob patterns in the content array use standard glob syntax. The double-star ** matches any number of directory levels. Curly braces {} match multiple extensions. Be as specific as possible — avoid patterns that are too broad (like ./**/*) as they will slow down scanning by including files like images and JSON that cannot contain class names.

// tailwind.config.js
module.exports = {
  content: [
    './src/**/*.{html,js,jsx,ts,tsx,vue}',
    './components/**/*.{js,jsx,ts,tsx}',
    './pages/**/*.{js,jsx,ts,tsx}',
    './layouts/**/*.html',
    // Include a specific file
    './public/index.html',
    // Include node_modules (for UI library components)
    './node_modules/@my-ui/components/dist/**/*.js',
  ],
};

Content for Popular Frameworks

Different frameworks organize their files differently. Here are the correct content patterns for the most popular setups. Next.js needs app/ and pages/ directories. Vue projects typically use .vue files. Laravel's Blade templates live in resources/views/. Always check that your entry files (like index.html or layout files) are included explicitly if they sit outside your glob patterns.

// Next.js App Router
content: ['./app/**/*.{js,jsx,ts,tsx}', './components/**/*.{js,jsx,ts,tsx}']

// Vue + Vite
content: ['./index.html', './src/**/*.{vue,js,ts}']

// Laravel Blade
content: ['./resources/**/*.blade.php', './resources/**/*.js']

// Nuxt 3 (usually auto-detected, but explicit)
content: ['./components/**/*.vue', './pages/**/*.vue', './layouts/**/*.vue']

The safelist Option

Sometimes classes are constructed at runtime and cannot be detected by static scanning — for example, class names built from CMS content, user input, or API responses. Use the safelist option to force-include specific classes or patterns, ensuring they are always in the output regardless of whether the scanner finds them. You can safelist individual strings or regex patterns.

// tailwind.config.js
module.exports = {
  safelist: [
    // Individual classes
    'text-red-500',
    'bg-blue-100',
    // Pattern: all bg-{color}-{shade} for red and green
    {
      pattern: /bg-(red|green)-(100|200|300|400|500)/,
    },
    // Include hover variants too
    {
      pattern: /bg-red-(400|500)/,
      variants: ['hover', 'focus'],
    },
  ],
};

The blocklist Option

The blocklist option is the opposite of safelist — it prevents specific classes from being included in the output even if the scanner finds them in your source. This is useful for enforcing team conventions (preventing use of deprecated utility names) or reducing output size by explicitly excluding utilities you know you will never use, like certain font size or animation classes.

// tailwind.config.js
module.exports = {
  blocklist: [
    // Prevent these classes from being generated
    'container',
    'prose',
    'animate-bounce',
  ],
};

Content Transformers

For files that need preprocessing before scanning — like .pug templates, .md files, or custom template engines — Tailwind's content.transform option lets you provide a function that transforms the raw file content into a string of class names. This is rarely needed but powerful for edge cases where the file format hides class names in a non-obvious way.

// tailwind.config.js
module.exports = {
  content: {
    files: ['./src/**/*.{html,js}'],
    transform: {
      // Transform markdown files before scanning
      md: (content) => {
        // Render to HTML first so class names are visible
        return renderMarkdownToHtml(content);
      },
    },
  },
};

Content Extraction for Component Libraries

If your project uses a third-party component library that ships pre-built JavaScript with embedded Tailwind classes, you need to include the library's dist files in your content array. Many popular Tailwind component libraries (like Flowbite, daisyUI, or custom internal libraries) work this way. Add the path to their built JavaScript output so the scanner can detect which classes they use.

// tailwind.config.js
module.exports = {
  content: [
    './src/**/*.{html,js,jsx,ts,tsx}',
    // Include prebuilt components from a library
    './node_modules/flowbite/**/*.js',
    // Or a local package in a monorepo
    '../../packages/ui/src/**/*.{js,jsx,ts,tsx}',
  ],
};

Verifying Your Content Config

To confirm that your content configuration is working correctly, run npx tailwindcss build and check the output file size. A well-configured production build should be under 50 KB (often much less). You can also run the Tailwind CLI with the --watch flag during development to see real-time compilation and verify that adding a new class immediately appears in the output.

# Build and check output size
npx tailwindcss -i ./src/input.css -o ./dist/output.css --minify

# Check the size
wc -c < ./dist/output.css  # bytes
ls -lh ./dist/output.css   # human-readable

# Watch mode for development
npx tailwindcss -i ./src/input.css -o ./dist/output.css --watch

JIT and On-Demand Class Generation

Tailwind v3 uses a Just-In-Time (JIT) engine by default. Unlike the old PurgeCSS approach, JIT generates classes on demand as you write them, scanning your content files in real time during development. This means your development CSS is already small and matches production exactly — there is no separate purging step in v3. The content array serves both development scanning and production optimization.

Common Content Configuration Mistakes

The most common mistake is missing files from the content array — classes from those files get purged in production. Another mistake is dynamic class construction where the full class name never appears as a string. A third issue is forgetting template files in non-JS frameworks. Always test your production build locally with NODE_ENV=production to catch purging issues before deploying.

// Common mistake: incomplete pattern
content: ['./src/**/*.js']  // MISSES .jsx, .tsx, .html files!

// Better: cover all template types
content: ['./src/**/*.{html,js,jsx,ts,tsx}']

// Also common: missing the root HTML file
content: [
  './index.html',              // don't forget this!
  './src/**/*.{js,jsx,ts,tsx}'
]

Quick Check

Test your understanding of Tailwind's content paths and class purging.

Lesson Recap

In this lesson you learned: the content array tells Tailwind which files to scan for class names, full class names must always appear as literal strings for the scanner to detect them, and the safelist option force-includes classes that cannot be statically detected. Next up we explore the difference between extending and overriding the Tailwind theme.

常见问题解答

「内容路径与清除未使用样式」课时是免费的吗?

是的 — 「内容路径与清除未使用样式」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Tailwind CSS Academy 课程的其余内容,请升级到 CoddyKit PRO。 Tailwind CSS Academy 课程共包含 4 节课。

「内容路径与清除未使用样式」这节课中我会学到什么?

正确配置 content 数组,确保 Tailwind 扫描所有文件,并在生产构建中移除未使用的 class。 你通过在浏览器中直接运行的动手代码来练习 Tailwind CSS Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Tailwind CSS Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Tailwind CSS Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「内容路径与清除未使用样式」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Tailwind CSS Academy 课中编写并运行代码吗?

能。每节 Tailwind CSS Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. tailwind.config.js 的结构
  2. 内容路径与清除未使用样式
  3. 扩展主题与覆盖主题
  4. 添加与配置插件
← 返回 Tailwind CSS Academy