核心概念
使用变体在暗黑模式下设置网站样式。
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");
当使用单体仓库时,这可能很有用,在这种情况下,你的构建命令从单体仓库的根目录而不是每个项目的根目录运行。
如果你要显式注册所有源,请使用 source(none)
完全禁用自动源检测
@import "tailwindcss" source(none);@source "../admin";@source "../shared";
这在具有多个 Tailwind 样式表的项目中可能很有用,你希望确保每个样式表仅包含每个样式表所需的类。