Core concepts
使用 variants 来为你的网站添加深色模式样式。
Tailwind 通过扫描你的项目中的工具类,然后基于你实际使用的类生成所有必要的 CSS。
这确保了你的 CSS 尽可能小,同时也使得像任意值这样的功能成为可能。
Tailwind 将你的所有源文件都视为纯文本,不会试图以任何方式将你的文件解析为代码。
相反,它只是在你的文件中查找根据 Tailwind 期望在类名中出现的字符可能是类名的任何标记:
export function Button({ color, children }) { const colors = { black: "bg-black text-white", blue: "bg-blue-500 text-white", white: "bg-white text-black", }; return ( <button className={`${colors[color]} rounded-full px-2 py-1.5 font-sans text-sm/6 font-medium shadow`}> {children} </button> );}然后它尝试为所有这些标记生成 CSS,丢弃框架不知道的任何不对应工具类的标记。
由于 Tailwind 将你的源文件扫描为纯文本,它无法理解你正在使用的编程语言中的字符串拼接或插值。
不要动态构造类名
<div class="text-{{ error ? 'red' : 'green' }}-600"></div>在上面的例子中,字符串 text-red-600 和 text-green-600 并不存在,所以 Tailwind 不会生成这些类。
相反,请确保你使用的任何类名都完整存在:
始终使用完整的类名
<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>如果你使用像 React 或 Vue 这样的组件库,这意味着你不应该使用 props 来动态构造类名:
不要使用 props 动态构建类名
function Button({ color, children }) { return <button className={`bg-${color}-600 hover:bg-${color}-500 ...`}>{children}</button>;}相反,将 props 映射到在构建时可静态检测的完整类名:
始终将 props 映射到静态类名
function Button({ color, children }) { const colorVariants = { blue: "bg-blue-600 hover:bg-blue-500", red: "bg-red-600 hover:bg-red-500", }; return <button className={`${colorVariants[color]} ...`}>{children}</button>;}这还有一个额外的好处,就是让你可以将不同的 prop 值映射到不同的颜色阴影,例如:
function Button({ color, children }) { const colorVariants = { blue: "bg-blue-600 hover:bg-blue-500 text-white", red: "bg-red-500 hover:bg-red-400 text-white", yellow: "bg-yellow-300 hover:bg-yellow-400 text-black", }; return <button className={`${colorVariants[color]} ...`}>{children}</button>;}只要你在代码中始终使用完整的类名,Tailwind 每次都会完美地生成你的所有 CSS。
Tailwind 将扫描你项目中的每个文件以查找类名,但以下情况除外:
.gitignore 文件中的文件如果你需要扫描 Tailwind 默认忽略的任何文件,你可以显式注册这些源。
使用 @source 来显式注册 Tailwind 默认忽略的源路径:
@import "tailwindcss";@source "../node_modules/@acmecorp/ui-lib";当你需要扫描使用 Tailwind 构建的外部库时,这特别有用,因为依赖项通常在你的 .gitignore 文件中列出并被 Tailwind 忽略。
Tailwind 默认使用当前工作目录作为扫描类名时的起点。
要显式设置源检测的基路径,请在 CSS 中导入 Tailwind 时使用 source() 函数:
@import "tailwindcss" source("../src");这在使用 monorepos 时特别有用,因为你的构建命令通常从 monorepo 的根目录而不是每个项目的根目录运行。
如果你想显式注册所有源,可以使用 source(none) 完全禁用自动源检测:
@import "tailwindcss" source(none);@source "../admin";@source "../shared";这在有多个 Tailwind 样式表的项目中特别有用,因为你希望确保每个样式表只包含每个样式表需要的类。