核心概念
使用變體在深色模式下設定網站樣式。
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 樣式表的專案中非常有用,您可以使用它來確保每個樣式表僅包含其需要的類別。