文章目錄
- 前言
- ? 一、集成 Tailwind CSS 到 React 項目
- 1. 安裝依賴
- 2. 配置 `tailwind.config.js`
- 3. 創建全局樣式文件(如 `src/index.css`)
- @tailwind base;
- @tailwind components;
- @tailwind utilities;
- 4. 在 `main.tsx` 或 `main.jsx` 中引入樣式
- ? 二、自定義樣式方式匯總
- 1. `theme.extend` 自定義主題(推薦)
- 2. 添加自定義組件類(@layer)
- 3. 插件方式自定義(如 `typography`、`forms`)
- 擴展:
- ? 一、什么是 Tailwind CSS 插件?
- ? 二、創建自定義插件的步驟
- 🧱 插件結構示意:
- ? 三、React 項目中使用該插件
- ? 四、高階用法:插件封裝為 NPM 包(組件庫開發)
- ? 五、自定義插件使用場景總結
- ? 是否支持 TypeScript?
- 4. 創建響應式自定義類
- 5. 使用 `cva`(class-variance-authority)封裝組件樣式(推薦大項目)
- ? 三、Tailwind CSS 常見優化建議
前言
在 React 項目中使用 Tailwind CSS 并進行自定義樣式配置,主要包括以下幾種方式和步驟:
? 一、集成 Tailwind CSS 到 React 項目
以 Vite 項目為例,集成步驟如下:
1. 安裝依賴
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
這會生成:
tailwind.config.js
postcss.config.js
2. 配置 tailwind.config.js
添加你的源碼路徑以啟用 JIT 模式下的 tree-shaking:
/** @type {import('tailwindcss').Config} */
export default {content: ["./index.html","./src/**/*.{js,ts,jsx,tsx}",],theme: {extend: {}, // 用于擴展自定義樣式},plugins: [],
}
3. 創建全局樣式文件(如 src/index.css
)
@tailwind base;
@tailwind components;
@tailwind utilities;
這是 Tailwind CSS 的核心指令,用于在你的 CSS 文件中引入 Tailwind 的三大層級樣式:
@tailwind base;
引入 Tailwind 的基礎樣式(reset/normalize、全局樣式、字體、表單等)。
作用類似于 CSS Reset,保證不同瀏覽器下的樣式一致性,并設置一些全局的基礎樣式。
@tailwind components;
引入 Tailwind 的組件類(如 container、按鈕等可復用的組件樣式)。
你也可以在這里通過 @layer components { … } 自定義自己的組件樣式。
@tailwind utilities;
引入 Tailwind 的工具類(如 p-4、text-center、bg-blue-500 等)。
這些是你在 JSX/HTML 里最常用的 Tailwind 類名。
4. 在 main.tsx
或 main.jsx
中引入樣式
import './index.css'
? 二、自定義樣式方式匯總
1. theme.extend
自定義主題(推薦)
位置:tailwind.config.js
theme: {extend: {colors: {primary: '#1e40af',danger: '#e11d48',},spacing: {'72': '18rem','84': '21rem',},fontFamily: {inter: ['Inter', 'sans-serif'],}},
}
然后你可以在組件中使用:
<div className="bg-primary text-white p-4">Hello</div>
2. 添加自定義組件類(@layer)
位置:index.css
或 global.css
@layer components {.btn-primary {@apply bg-blue-600 text-white px-4 py-2 rounded;}.card {@apply shadow-md rounded-lg p-6 bg-white;}
}
使用方式:
<button className="btn-primary">Click</button>
3. 插件方式自定義(如 typography
、forms
)
npm install @tailwindcss/forms @tailwindcss/typography
plugins: [require('@tailwindcss/forms'),require('@tailwindcss/typography'),
],
擴展:
Tailwind CSS 支持通過自定義插件(Plugin)來擴展樣式系統,這是構建 組件庫、設計系統 或 復用工具類 的關鍵手段之一。下面將從 原理、語法、示例和在 React 項目中的集成步驟,手把手講清楚 Tailwind CSS 自定義插件的用法。
? 一、什么是 Tailwind CSS 插件?
Tailwind 插件允許你通過 API 注冊新的:
- 工具類(utilities)
- 組件類(components)
- 自定義變體(variants)
- 基礎樣式(base)
? 二、創建自定義插件的步驟
🧱 插件結構示意:
// tailwind.config.js
const plugin = require('tailwindcss/plugin')module.exports = {content: [...],theme: {extend: {},},plugins: [plugin(function({ addUtilities, addComponents, addBase, matchUtilities, theme }) {// 1. 添加基礎樣式addBase({'h1': { fontSize: theme('fontSize.2xl') },'h2': { fontSize: theme('fontSize.xl') },})// 2. 添加組件類addComponents({'.btn': {padding: '0.5rem 1rem',borderRadius: '0.25rem',fontWeight: '600',},'.btn-primary': {backgroundColor: theme('colors.blue.500'),color: theme('colors.white'),},})// 3. 添加工具類addUtilities({'.text-shadow': {textShadow: '2px 2px #000000',},'.text-shadow-md': {textShadow: '4px 4px #000000',},})// 4. 響應式匹配工具類matchUtilities({'rotate-y': (value) => ({transform: `rotateY(${value})`,}),},{ values: theme('rotate') })})],
}
? 三、React 項目中使用該插件
只需將上面的 tailwind.config.js
插件注冊完成后,像平常一樣使用樣式類:
<button className="btn btn-primary text-shadow-md">Click Me</button>
無需其他導入!Tailwind 會自動根據你 content
中匹配到的類,生成 CSS。
? 四、高階用法:插件封裝為 NPM 包(組件庫開發)
你可以將插件封裝成獨立模塊:
// my-button-plugin.js
const plugin = require('tailwindcss/plugin')module.exports = plugin(({ addComponents, theme }) => {addComponents({'.btn-danger': {backgroundColor: theme('colors.red.500'),color: '#fff',padding: '0.5rem 1rem',borderRadius: '9999px',},})
})
然后在主配置中使用:
const myButtonPlugin = require('./my-button-plugin')module.exports = {plugins: [myButtonPlugin],
}
? 五、自定義插件使用場景總結
場景 | 使用方式 |
---|---|
提供通用按鈕/卡片/警告樣式 | addComponents |
增強工具類(如旋轉、投影) | addUtilities |
改變基礎標簽默認樣式 | addBase |
動態類支持(如 .rotate-y-45 ) | matchUtilities |
? 是否支持 TypeScript?
Tailwind 插件本質是 JS 函數,也可以使用 .ts
文件編寫,只要你在 tailwind.config.ts
中用 defineConfig()
包裹即可:
import plugin from 'tailwindcss/plugin'
import { defineConfig } from 'tailwindcss/helpers'export default defineConfig({plugins: [plugin(({ addUtilities }) => {addUtilities({'.skew-10deg': {transform: 'skewY(-10deg)'}})})]
})
4. 創建響應式自定義類
extend: {screens: {'xs': '480px',},maxWidth: {'8xl': '90rem',},
}
5. 使用 cva
(class-variance-authority)封裝組件樣式(推薦大項目)
import { cva } from 'class-variance-authority'const button = cva('px-4 py-2 rounded', {variants: {intent: {primary: 'bg-blue-600 text-white',secondary: 'bg-gray-600 text-white',},size: {sm: 'text-sm',lg: 'text-lg',},},defaultVariants: {intent: 'primary',size: 'sm',},
})
? 三、Tailwind CSS 常見優化建議
- ? 啟用 JIT 模式(默認)
- ? 用
@apply
抽離公共類 - ? 使用
cva
管理組件變體 - ? 移除未使用的類:
purge
(舊)→content
(新) - ? 使用 Tailwind plugin 編寫通用組件或設計系統