首页 / Tailwind CSS 入门教程 / 自动内容检测机制

Tailwind CSS 入门教程

自动内容检测机制

本教程共 50 篇 · 第 14 篇 · 更新于 2026-07-29 · 约 7 分钟阅读

Tailwind CSSTailwind CSS 入门教程内容检测源文件@source动态类名

14. 自动内容检测机制

本节目标:理解 Tailwind 怎么找到你用过的类、动态拼接类名为什么不行、怎么手动指定扫描路径。

Tailwind 不会生成所有可能的 CSS(那得有几十万行),而是只生成你用过的类。为了知道你用了哪些类,它要扫描你的源文件。

怎么扫描的

Tailwind 把源文件当纯文本处理,不解析代码语法。它用正则匹配所有看起来像类名的字符串,然后尝试生成对应的 CSS。

这意味着它能识别模板字符串里的类名:

function Button({ size, children }) {
  const sizeClasses = {
    md: "px-4 py-2 rounded-md text-base",
    lg: "px-5 py-3 rounded-lg text-lg",
  }[size];

  return (
    <button className={`font-bold ${sizeClasses}`}>
      {children}
    </button>
  );
}

px-4py-2rounded-md 这些字符串虽然嵌在 JS 对象里,但 Tailwind 能扫描到。

动态类名的坑

因为 Tailwind 不解析代码,拼接出来的类名它认不出来

<!-- 错误:Tailwind 看不到 text-red-600 或 text-green-600 -->
<div class="text-{{ error ? 'red' : 'green' }}-600">

<!-- 错误:bg-blue-600 不会被生成 -->
function Button({ color }) {
  return <button className={`bg-${color}-600`}>

正确做法:用完整的类名做映射:

function Button({ color, children }) {
  const colorVariants = {
    blue: "bg-blue-600 hover:bg-blue-500",
    red: "bg-red-600 hover:bg-red-500",
    yellow: "bg-yellow-300 hover:bg-yellow-400 text-black",
  };
  return (
    <button className={`${colorVariants[color]} px-4 py-2 rounded`}>
      {children}
    </button>
  );
}
Warning

永远不要让 Tailwind 去猜拼接的类名。要么写完整的类名,要么用 @source inline() 强制生成。

哪些文件会被扫描

默认情况下,Tailwind 扫描项目里除了以下之外的所有文件

  • .gitignore 里列出的文件
  • node_modules 目录
  • 二进制文件(图片、视频、zip 等)
  • CSS 文件
  • 包管理器锁文件(package-lock.jsonyarn.lock 等)

手动注册源:@source

如果需要扫描被默认忽略的文件(比如 node_modules 里的 UI 库),用 @source

@import "tailwindcss";
@source "../node_modules/@acmecorp/ui-lib";

设置基准路径

@import "tailwindcss" source("../src");

monorepo 项目里有用——告诉 Tailwind 从哪个目录开始扫。

排除特定路径

@import "tailwindcss";
@source not "../src/components/legacy";

完全禁用自动检测

@import "tailwindcss" source(none);
@source "../admin";
@source "../shared";

每个样式表只包含显式注册的源,适合多入口项目。

强制生成特定类:@source inline()

有些类名可能不在源文件里,但你确实需要(比如从数据库读取的),用 @source inline()

@import "tailwindcss";
@source inline("underline");

生成带变体的类:

@source inline("{hover:,focus:,}underline");

用花括号展开批量生成:

@source inline("{hover:,}bg-red-{50,{100..900..100},950}");

这会生成 bg-red-50bg-red-100、… bg-red-950,每个都带 hover: 变体。

排除特定类

反过来,你也可以阻止某些类生成:

@source not inline("{hover:,focus:,}bg-red-{50,{100..900..100},950}");

即使源文件里出现了这些类,也不会输出到 CSS。

Tip

大多数项目不需要手动配 @source。自动检测已经覆盖了 95% 的场景。只有用到外部库或者有特殊目录结构时才需要干预。

下一章我们看兼容性。