概觀

外掛程式讓你可以使用 JavaScript 註冊新的樣式,供 Tailwind 注入使用者的樣式表,而不是 CSS。

要開始使用您的第一個外掛程式,請從 tailwindcss/plugin 匯入 Tailwind 的 plugin 函式。然後在您的 plugins 陣列中,使用匿名函式作為第一個引數來呼叫匯入的 plugin 函式。

tailwind.config.js
const plugin = require('tailwindcss/plugin')

module.exports = {
  plugins: [
    plugin(function({ addUtilities, addComponents, e, config }) {
      // Add your custom styles here
    }),
  ]
}

外掛程式函式接收一個單一物件引數,可以 解構 成數個輔助函式

  • addUtilities(),用於註冊新的靜態公用程式樣式
  • matchUtilities(),用於註冊新的動態公用程式樣式
  • addComponents(),用於註冊新的靜態元件樣式
  • matchComponents(),用於註冊新的動態元件樣式
  • addBase(),用於註冊新的基礎樣式
  • addVariant(),用於註冊自訂靜態變異
  • matchVariant(),用於註冊自訂動態變異
  • theme(),用於在使用者的佈景主題設定中查詢值
  • config(),用於在使用者的 Tailwind 設定中查詢值
  • corePlugins(),用於檢查核心外掛程式是否已啟用
  • e(),用於手動跳脫用於類別名稱的字串

官方外掛程式

我們已經開發了一些官方外掛程式,用於一些流行的功能,這些功能由於某種原因還不屬於核心。

外掛程式可以透過 npm 安裝,然後將它們新增到您的 tailwind.config.js 檔案中,以將它們新增到您的專案中

tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  // ...
  plugins: [
    require('@tailwindcss/typography'),
    require('@tailwindcss/forms'),
    require('@tailwindcss/aspect-ratio'),
    require('@tailwindcss/container-queries'),
  ]
}

排版

@tailwindcss/typography 外掛程式新增一組 prose 類別,可用於快速將明智的排版樣式新增到來自 Markdown 或 CMS 資料庫等來源的內容區塊。

<article class="prose lg:prose-xl">
  <h1>Garlic bread with cheese: What the science tells us</h1>
  <p>
    For years parents have espoused the health benefits of eating garlic bread with cheese to their
    children, with the food earning such an iconic status in our culture that kids will often dress
    up as warm, cheesy loaf for Halloween.
  </p>
  <p>
    But a recent study shows that the celebrated appetizer may be linked to a series of rabies cases
    springing up around the country.
  </p>
  <!-- ... -->
</article>

深入了解排版外掛程式 →

表單

@tailwindcss/forms 外掛程式新增一個有觀點的表單重設層,讓使用公用程式類別來設定表單元素的樣式變得更簡單。

<!-- You can actually customize padding on a select element: -->
<select class="px-4 py-3 rounded-full">
  <!-- ... -->
</select>

<!-- Or change a checkbox color using text color utilities: -->
<input type="checkbox" class="rounded text-pink-500" />

深入了解表單外掛程式 →

長寬比

@tailwindcss/aspect-ratio 外掛是原生 aspect-ratio 支援的替代方案,可在較舊的瀏覽器中運作,並新增 aspect-w-{n}aspect-h-{n} 類別,可組合使用以賦予元素固定的長寬比。

<div class="aspect-w-16 aspect-h-9">
  <iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>

深入了解長寬比外掛 →

容器查詢

@tailwindcss/container-queries 外掛新增 @{size} 變異,例如 @sm@md,讓您可以根據標記為 @container 的父層尺寸,而不是視窗,來設定元素樣式。

<div class="@container">
  <div class="@lg:text-sky-400">
    <!-- ... -->
  </div>
</div>

深入了解容器查詢外掛 →


新增實用程式

addUtilitiesmatchUtilities 函數允許您在 Tailwind 的 utilities 層中註冊新的樣式。

與 Tailwind 預設包含的實用程式一樣,外掛新增的實用程式僅會在專案中實際使用時,才會包含在產生的 CSS 中。

靜態工具程式

使用 addUtilities 函式來註冊不支援使用者提供值的簡單靜態工具程式

tailwind.config.js
const plugin = require('tailwindcss/plugin')

module.exports = {
  plugins: [
    plugin(function({ addUtilities }) {
      addUtilities({
        '.content-auto': {
          'content-visibility': 'auto',
        },
        '.content-hidden': {
          'content-visibility': 'hidden',
        },
        '.content-visible': {
          'content-visibility': 'visible',
        },
      })
    })
  ]
}

CSS-in-JS 語法 參考中進一步了解如何在 JavaScript 中表示您的樣式。

動態工具程式

使用 matchUtilities 函式來註冊對應到使用者 theme 組態中定義值的工具程式

tailwind.config.js
const plugin = require('tailwindcss/plugin')

module.exports = {
  theme: {
    tabSize: {
      1: '1',
      2: '2',
      4: '4',
      8: '8',
    }
  },
  plugins: [
    plugin(function({ matchUtilities, theme }) {
      matchUtilities(
        {
          tab: (value) => ({
            tabSize: value
          }),
        },
        { values: theme('tabSize') }
      )
    })
  ]
}

以這種方式定義的工具程式也支援 任意值,這表示您可以使用方括號表示法來使用主題中不存在的值

<div class="tab-[13]">
  <!-- ... -->
</div>

前綴和重要

預設情況下,外掛程式工具程式會自動遵循使用者的 prefiximportant 偏好設定。

這表示給定這個 Tailwind 組態

tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  prefix: 'tw-',
  important: true,
  // ...
}

…上述範例外掛會產生下列 CSS

.tw-content-auto {
  content-visibility: auto !important;
}
.tw-content-hidden {
  content-visibility: hidden !important;
}
.tw-content-visible {
  content-visibility: visible !important;
}

搭配修飾詞使用

使用 addUtilities 新增的任何自訂工具程式,都可以自動搭配修飾詞使用

<div class="content-auto lg:content-visible">
  <!-- ... -->
</div>

游標移入、焦點及其他狀態 文件中了解更多資訊。

提供預設值

工具程式外掛可以透過將組態物件包含在 plugin 函式的第二個引數中,來提供預設值

./plugins/tab-size.js
const plugin = require('tailwindcss/plugin')

module.exports = plugin(function({ matchUtilities, theme }) {
  matchUtilities(
    {
      tab: (value) => ({
        tabSize: value
      }),
    },
    { values: theme('tabSize') }
  )
}, {
  theme: {
    tabSize: {
      1: '1',
      2: '2',
      4: '4',
      8: '8',
    }
  }
})

這些值與預設組態中的值行為相同,而且可以由最終使用者覆寫或延伸。


新增元件

addComponents 函式允許您在 Tailwind 的 components 層中註冊新的樣式。

使用它來新增更多有觀點、複雜的類別,例如按鈕、表單控制項、警示等;這類預建元件在其他框架中很常見,您可能需要使用工具程式類別來覆寫它們。

若要從外掛程式新增新的元件樣式,請呼叫 addComponents,並使用 CSS-in-JS 語法 傳入您的樣式

tailwind.config.js
const plugin = require('tailwindcss/plugin')

module.exports = {
  plugins: [
    plugin(function({ addComponents }) {
      addComponents({
        '.btn': {
          padding: '.5rem 1rem',
          borderRadius: '.25rem',
          fontWeight: '600',
        },
        '.btn-blue': {
          backgroundColor: '#3490dc',
          color: '#fff',
          '&:hover': {
            backgroundColor: '#2779bd'
          },
        },
        '.btn-red': {
          backgroundColor: '#e3342f',
          color: '#fff',
          '&:hover': {
            backgroundColor: '#cc1f1a'
          },
        },
      })
    })
  ]
}

與 Tailwind 中的其他元件類別一樣,由外掛程式新增的元件類別只會在專案中實際使用時才包含在產生的 CSS 中。

前綴和重要

預設情況下,元件類別會自動遵循使用者的 prefix 偏好,但不受 使用者的 important 偏好影響。

這表示給定這個 Tailwind 組態

tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  prefix: 'tw-',
  important: true,
  // ...
}

…上述範例外掛會產生下列 CSS

.tw-btn {
  padding: .5rem 1rem;
  border-radius: .25rem;
  font-weight: 600;
}
.tw-btn-blue {
  background-color: #3490dc;
  color: #fff;
}
.tw-btn-blue:hover {
  background-color: #2779bd;
}
.tw-btn-red {
  background-color: #e3342f;
  color: #fff;
}
.tw-btn-red:hover {
  background-color: #cc1f1a;
}

雖然很少有充分的理由讓元件宣告變得重要,但如果您真的需要這樣做,您隨時可以手動新增 !important

tailwind.config.js
const plugin = require('tailwindcss/plugin')

module.exports = {
  plugins: [
    plugin(function({ addComponents }) {
      addComponents({
        '.btn': {
          padding: '.5rem 1rem !important',
          borderRadius: '.25rem !important',
          fontWeight: '600 !important',
        },
        // ...
      })
    })
  ]
}

選擇器中的所有類別預設都會加上前綴,因此如果您新增更複雜的樣式,例如

tailwind.config.js
const plugin = require('tailwindcss/plugin')

module.exports = {
  prefix: 'tw-',
  plugins: [
    plugin(function({ addComponents }) {
      const components = {
        // ...
        '.navbar-inverse a.nav-link': {
            color: '#fff',
        }
      }

      addComponents(components)
    })
  ]
}

…將會產生以下 CSS

.tw-navbar-inverse a.tw-nav-link {
    color: #fff;
}

搭配修飾詞使用

使用 addComponents 新增的任何元件類別都可以自動與修改器一起使用

<div class="btn md:btn-lg">
  <!-- ... -->
</div>

游標移入、焦點及其他狀態 文件中了解更多資訊。


新增基本樣式

addBase 函數可讓您在 Tailwind 的 base 層中註冊新的樣式。使用它來新增基本字體樣式、自訂的全局重設或 @font-face 規則。

若要從外掛程式新增新的基本樣式,請呼叫 addBase,並使用 CSS-in-JS 語法傳入您的樣式

tailwind.config.js
const plugin = require('tailwindcss/plugin')

module.exports = {
  plugins: [
    plugin(function({ addBase, theme }) {
      addBase({
        'h1': { fontSize: theme('fontSize.2xl') },
        'h2': { fontSize: theme('fontSize.xl') },
        'h3': { fontSize: theme('fontSize.lg') },
      })
    })
  ]
}

由於基本樣式用於鎖定像 divh1 這樣的裸選擇器,因此它們不會尊重使用者的 prefiximportant 組態。


新增變體

addVariantmatchVariant 函數可讓您註冊自己的自訂 修飾詞,這些修飾詞可用於內建變體,例如 hoverfocussupports

靜態變體

對於簡單的自訂變體,請使用 addVariant 函數,傳入自訂變體的名稱,以及表示如何修改選擇器的格式字串。

tailwind.config.js
const plugin = require('tailwindcss/plugin')

module.exports = {
  // ...
  plugins: [
    plugin(function({ addVariant }) {
      addVariant('optional', '&:optional')
      addVariant('hocus', ['&:hover', '&:focus'])
      addVariant('inverted-colors', '@media (inverted-colors: inverted)')
    })
  ]
}

第一個參數是使用者在 HTML 中會使用的修改器名稱,因此以上的範例會讓撰寫像這樣的類別成為可能

<form class="flex inverted-colors:outline ...">
  <input class="optional:border-gray-300 ..." />
  <button class="bg-blue-500 hocus:bg-blue-600">...</button>
</form>

動態變體

使用 matchVariant 函式來註冊新的參數化變體,例如內建的 supports-*data-*aria-* 變體

tailwind.config.js
const plugin = require('tailwindcss/plugin')

module.exports = {
  plugins: [
    plugin(function({ matchVariant }) {
      matchVariant(
        'nth',
        (value) => {
          return `&:nth-child(${value})`;
        },
        {
          values: {
            1: '1',
            2: '2',
            3: '3',
          }
        }
      );
    })
  ]
}

使用 matchVariant 定義的變體也支援使用方括號表示法指定任意值

<div class="nth-[3n+1]:bg-blue-500 ...">
  <!-- ... -->
</div>

使用 sort 選項來控制產生的 CSS 的來源順序,以避免與來自相同變體的其他值發生優先順序問題

matchVariant("min", (value) => `@media (min-width: ${value})`, {
  sort(a, z) {
    return parseInt(a.value) - parseInt(z.value);
  },
});

父代和兄弟元素狀態

您的自訂修改器不會自動與 Tailwind 的 父代兄弟元素 狀態修改器搭配使用。

若要支援您自訂修改器的 group-*peer-* 版本,請使用特殊的 :merge 指令將它們註冊為個別變體,以確保 .group.peer 類別只在最後的選擇器中出現一次。

tailwind.config.js
const plugin = require('tailwindcss/plugin')

module.exports = {
  // ...
  plugins: [
    plugin(function({ addVariant }) {
      addVariant('optional', '&:optional')
      addVariant('group-optional', ':merge(.group):optional &')
      addVariant('peer-optional', ':merge(.peer):optional ~ &')
    })
  ]
}

擴充設定

外掛可以透過提供一個物件作為 plugin 函式的第二個引數,將其自訂設定值合併到使用者的 tailwind.config.js 設定中

./plugins/tab-size.js
const plugin = require('tailwindcss/plugin')

module.exports = plugin(function({ matchUtilities, theme }) {
  matchUtilities(
    {
      tab: (value) => ({
        tabSize: value
      }),
    },
    { values: theme('tabSize') }
  )
}, {
  theme: {
    tabSize: {
      1: '1',
      2: '2',
      4: '4',
      8: '8',
    }
  }
})

這對於提供外掛產生的類別預設 theme 值等情況很有用。


公開選項

有時候讓外掛以不屬於 theme 的方式進行設定是有道理的,例如您可能希望使用者能夠自訂外掛使用的類別名稱。

在這種情況下,您可以使用 plugin.withOptions 來定義一個可以使用設定物件呼叫的外掛。此 API 與一般的 plugin API 類似,只不過每個引數都應該是一個函式,接收使用者的 options 並傳回您通常使用一般 API 傳入的值

./plugins/markdown.js
const plugin = require('tailwindcss/plugin')

module.exports = plugin.withOptions(function (options = {}) {
  return function({ addComponents }) {
    const className = options.className ?? 'markdown'

    addComponents({
      [`.${className}`]: {
        // ...
      }
    })
  }
}, function (options) {
  return {
    theme: {
      markdown: {
        // ...
      }
    },
  }
})

使用者會在 plugins 設定中註冊外掛時傳入其選項來呼叫您的外掛

tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    // ...
  },
  plugins: [
    require('./plugins/markdown.js')({
      className: 'wysiwyg'
    })
  ],
}

使用者也可以註冊以這種方式建立的外掛程式,通常不需要呼叫它們,如果他們不需要傳遞任何自訂選項

tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    // ...
  },
  plugins: [
    require('./plugins/markdown.js')
  ],
}

CSS-in-JS 語法

Tailwind 的外掛程式系統預期 CSS 規則寫成 JavaScript 物件,使用與您可能從 CSS-in-JS 函式庫(例如 Emotion)認識的相同語法,由 postcss-js 在幕後提供支援。

考慮這個簡單的 CSS 規則

.card {
  background-color: #fff;
  border-radius: .25rem;
  box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

將其轉換為 CSS-in-JS 物件會如下所示

addComponents({
  '.card': {
    'background-color': '#fff',
    'border-radius': '.25rem',
    'box-shadow': '0 2px 4px rgba(0,0,0,0.2)',
  }
})

為方便起見,屬性名稱也可以寫成 camelCase,並且會自動轉換為 dash-case

addComponents({
  '.card': {
    backgroundColor: '#fff',
    borderRadius: '.25rem',
    boxShadow: '0 2px 4px rgba(0,0,0,0.2)',
  }
})

巢狀結構也受支援(由 postcss-nested 提供支援),使用您可能熟悉 Sass 或 Less 的相同語法

addComponents({
  '.card': {
    backgroundColor: '#fff',
    borderRadius: '.25rem',
    boxShadow: '0 2px 4px rgba(0,0,0,0.2)',
    '&:hover': {
      boxShadow: '0 10px 15px rgba(0,0,0,0.2)',
    },
    '@media (min-width: 500px)': {
      borderRadius: '.5rem',
    }
  }
})

可以在同一個物件中定義多個規則

addComponents({
  '.btn': {
    padding: '.5rem 1rem',
    borderRadius: '.25rem',
    fontWeight: '600',
  },
  '.btn-blue': {
    backgroundColor: '#3490dc',
    color: '#fff',
    '&:hover': {
      backgroundColor: '#2779bd'
    },
  },
  '.btn-red': {
    backgroundColor: '#e3342f',
    color: '#fff',
    '&:hover': {
      backgroundColor: '#cc1f1a'
    },
  },
})

…或作為物件陣列,以防您需要重複相同的鍵

addComponents([
  {
    '@media (min-width: 500px)': {
      // ...
    }
  },
  {
    '@media (min-width: 500px)': {
      // ...
    }
  },
  {
    '@media (min-width: 500px)': {
      // ...
    }
  },
])