---
title: "Tailwind CSS 與 React.js：打造現代前端開發環境"
description: "本文深入探討了 Tailwind CSS 的眾多優勢，以及如何在 Vite 驅動的 React.js 專案中有效實施它。通過整合這兩種強大技術，開發者可以顯著提升開發效率，同時維持高度自訂的設計靈活性。本文還將展示如何構建一個精美的登入表單，並探討如何結合 SCSS 與 Tailwind CSS 來優化您的前端開發流程。"
slug: "tailwind-css-reactjs-modern-frontend-development"
date: 2025-03-26T00:00:00.000Z
url: https://calpa.me/blog/tailwind-css-reactjs-modern-frontend-development/
---

> ⚠️ **時效警告**：本文發佈於 2025 年 3 月，主體流程基於當時的 Tailwind CSS v4；其中「結合 SCSS」一章節以 postcss-import 載入 .scss 並跨檔案使用 @apply 的寫法難以直接運作，實作時請以 Tailwind 官方文件為準。內容保留作為歷史紀錄。

## Tailwind CSS 的主要優勢

Tailwind CSS 作為一個實用優先（utility-first）的 CSS 框架，提供了許多傳統 CSS 方法所不具備的優勢。以下是採用 Tailwind CSS 的主要好處：

### 高效率的開發過程

Tailwind CSS 通過其實用優先的方法簡化了開發過程。這個框架使您能夠直接在 HTML 元素中應用預定義的類，而不必為每個組件編寫自定義 CSS。這種方法不僅加快了開發速度，還保持了代碼庫的清晰和組織。

透過提供大量的實用優先類別，Tailwind CSS 顯著加速了 Web 開發。這種效率意味著開發者可以更快地建立原型和網站，更有效地滿足緊迫的項目期限。

### 一致性與可維護性

Tailwind CSS 通過預設值確保整個應用程序的一致性。您不必處理顏色、邊距、字體大小等值，因為它們已經預先定義好了。

此外，由於只編譯實際使用的 CSS，Tailwind CSS 保持了較小的體積，這對於性能至關重要。PurgeCSS 功能確保只有在項目中實際使用的樣式才會包含在最終的 CSS 文件中。

### 高度自訂性

儘管 Tailwind CSS 提供了大量預設，但它並不限制創意自由。通過配置文件，設計師可以根據專案的具體需求進行全面的定制。這種靈活性使 Tailwind CSS 成為那些希望在效率和創意之間取得平衡的開發者的理想選擇。

### 響應式設計功能

Tailwind CSS 使創建響應式佈局變得簡單。其實用類別被設計為在所有尺寸的設備上無縫工作，幫助開發者為現代多設備環境構建網站。

### 項目間可移植性

使用 Tailwind CSS 的一個重要優勢是，只要所有項目都使用 Tailwind，組件就可以在不同項目之間幾乎完全自由地移動。這種可移植性對於管理多個項目或在團隊間共享組件的團隊來說是一個顯著的好處。

## 在 Vite 驅動的 React.js 專案中實施 Tailwind CSS

![Vite](https://assets.calpa.me/vite-header.avif)

### 環境設置

要開始一個新的 React + Vite + Tailwind CSS 專案，請按照以下步驟操作：

1. **建立一個新的 Vite React 專案**：

   ```bash
   npm create vite@latest tailwindcss-react -- --template react
   cd tailwindcss-react
   ```

2. **安裝 Tailwind CSS 及其依賴**：

   ```bash
   npm install tailwindcss @tailwindcss/vite
   ```

3. **將 @tailwindcss/vite 插件添加到 Vite 配置**：

   在專案根目錄創建或修改 `vite.config.js`：

   ```javascript
   import { defineConfig } from "vite";
   import react from "@vitejs/plugin-react";
   import tailwindcss from "@tailwindcss/vite";

   export default defineConfig({
     plugins: [react(), tailwindcss()],
   });
   ```

4. **在 CSS 文件中導入 Tailwind CSS**：

   在您的主 CSS 文件（例如 `src/index.css`）中添加以下內容：

   ```css
   @import "tailwindcss";
   ```

5. **運行開發伺服器**：

   ```bash
   npm run dev
   ```

至此，您的 Vite + React 專案已經成功集成了 Tailwind CSS，可以開始使用 Tailwind 的實用類來設計您的內容。

## 結合 SCSS 與 Tailwind CSS

![SCSS](https://assets.calpa.me/scss.avif)

在同一個專案中結合 SCSS 與 Tailwind CSS 可以為您的開發流程帶來更多靈活性。以下是如何實施：

### 安裝必要的依賴

```bash
npm install postcss-import postcss-nested
```

### 修改 postcss.config.js

更新您的 `postcss.config.js` 文件以包含必要的插件：

```javascript
module.exports = {
  plugins: {
    "postcss-import": {},
    "postcss-nested": {},
    autoprefixer: {},
  },
};
```

### 更新 CSS 文件結構

修改您的主 CSS 文件以導入 Tailwind CSS 樣式：

```css
@import "tailwindcss";

/* 樣式導入 */
@import "./styles/styles.scss";
```

### 創建 SCSS 樣式文件

在 `src/styles` 文件夾中創建一個 SCSS 文件（例如 `styles.scss`），您可以在其中定義自定義類：

```scss
.btn {
  @apply py-2 px-4 rounded font-semibold;

  &.btn-primary {
    @apply bg-blue-500 text-white hover:bg-blue-600 transition duration-300;
  }

  &.btn-secondary {
    @apply bg-gray-200 text-gray-800 hover:bg-gray-300 transition duration-300;
  }
}

.form-input {
  @apply w-full p-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500;
}
```

這種方法允許您創建可重用的 SCSS 類，這些類利用 Tailwind 的 `@apply` 指令來整合 Tailwind 的實用類，從而避免在 HTML 中使用冗長的類字符串。

## 構建一個漂亮的登入表單

![Tailwind CSS](https://assets.calpa.me/tailwindcss-react-login-form.avif)

以下是使用 React、Tailwind CSS 和我們的自定義 SCSS 類創建的登入表單示例：

```jsx
import React, { useState } from "react";

const Login = () => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log("Email:", email);
    console.log("Password:", password);
    // 在這裡添加認證邏輯
  };

  return (
    <div className="flex items-center justify-center min-h-screen bg-gray-100">
      <div className="bg-white p-8 rounded-xl shadow-lg max-w-md w-full">
        <h2 className="text-2xl font-bold mb-6 text-center">登入</h2>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label
              htmlFor="email"
              className="block text-sm font-medium text-gray-700 mb-1"
            >
              電子郵件
            </label>
            <input
              id="email"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="form-input"
              placeholder="請輸入您的電子郵件"
              required
            />
          </div>
          <div>
            <label
              htmlFor="password"
              className="block text-sm font-medium text-gray-700 mb-1"
            >
              密碼
            </label>
            <input
              id="password"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="form-input"
              placeholder="請輸入您的密碼"
              required
            />
          </div>
          <div className="flex items-center justify-between">
            <div className="flex items-center">
              <input
                id="remember-me"
                type="checkbox"
                className="h-4 w-4 text-blue-500 border-gray-300 rounded"
              />
              <label
                htmlFor="remember-me"
                className="ml-2 block text-sm text-gray-700"
              >
                記住我
              </label>
            </div>
            <a href="#" className="text-sm text-blue-500 hover:text-blue-700">
              忘記密碼？
            </a>
          </div>
          <button type="submit" className="btn btn-primary w-full">
            登入
          </button>
        </form>
        <div className="mt-6">
          <div className="relative">
            <div className="absolute inset-0 flex items-center">
              <div className="w-full border-t border-gray-300"></div>
            </div>
            <div className="relative flex justify-center text-sm">
              <span className="px-2 bg-white text-gray-500">
                或透過其他方式登入
              </span>
            </div>
          </div>

          <div className="mt-6 grid grid-cols-3 gap-3">
            <button className="btn flex justify-center items-center bg-gray-100 hover:bg-gray-200">
              <svg className="h-5 w-5" fill="currentColor" viewBox="0 0 24 24">
                <path d="M12 0c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm-2.917 16.083c-2.258 0-4.083-1.825-4.083-4.083s1.825-4.083 4.083-4.083c1.103 0 2.024.402 2.735 1.067l-1.107 1.068c-.304-.292-.834-.63-1.628-.63-1.394 0-2.531 1.155-2.531 2.579 0 1.424 1.138 2.579 2.531 2.579 1.616 0 2.224-1.162 2.316-1.762h-2.316v-1.4h3.855c.036.204.064.408.064.677.001 2.332-1.563 3.988-3.919 3.988z" />
              </svg>
            </button>
            <button className="btn flex justify-center items-center bg-blue-600 hover:bg-blue-700 text-white">
              <svg className="h-5 w-5" fill="currentColor" viewBox="0 0 24 24">
                <path d="M12 0c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm-2 16h-2v-6h2v6zm-1-6.891c-.607 0-1.1-.496-1.1-1.109 0-.612.492-1.109 1.1-1.109s1.1.497 1.1 1.109c0 .613-.493 1.109-1.1 1.109zm8 6.891h-1.998v-2.861c0-1.881-2.002-1.722-2.002 0v2.861h-2v-6h2v1.093c.872-1.616 4-1.736 4 1.548v3.359z" />
              </svg>
            </button>
            <button className="btn flex justify-center items-center bg-gray-800 hover:bg-black text-white">
              <svg className="h-5 w-5" fill="currentColor" viewBox="0 0 24 24">
                <path d="M12 0c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm3 8h-1.35c-.538 0-.65.221-.65.778v1.222h2l-.209 2h-1.791v7h-3v-7h-2v-2h2v-2.308c0-1.769.931-2.692 3.029-2.692h1.971v3z" />
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;
```

這個示例展示了如何使用 Tailwind CSS 的實用類和我們之前定義的自定義 SCSS 類（如 `.form-input` 和 `.btn`）來創建一個現代、響應式的登入表單。

你也可以瀏覽我的 [Tailwind CSS React Demo](https://github.com/calpa/tailwindcss-react) 來了解更多。

## 結論

![Tailwind CSS](https://assets.calpa.me/marc-olivier-jodoin-NqOInJ-ttqM-unsplash.avif)

Tailwind CSS 為現代前端開發提供了一種高效且靈活的方法，尤其是當與 React.js 和 Vite 等工具結合使用時。通過採用實用優先的方法，開發者可以更快地構建精美、響應式的界面，同時保持代碼的可維護性和一致性。

將 SCSS 與 Tailwind CSS 結合使用，可以解決長類名的問題，同時保持 Tailwind 的所有優勢。這種混合方法特別適合那些希望平衡開發速度和代碼可讀性的團隊。

無論您是正在構建一個新項目還是優化現有的代碼庫，Tailwind CSS 都提供了強大的工具集，使您能夠創建既美觀又功能強大的用戶界面。

## 參考資源

- Tailwind CSS 官方文檔：https://tailwindcss.com/docs/installation/using-vite
