🛠️ CSS 工程化

CSS Modules、CSS-in-JS、Tailwind CSS、CSS Variables 的对比与演示

1. CSS 工程化方案对比

方案 作用域 运行时 动态样式 类型安全 适用场景
CSS Modules ✅ 局部 ❌ 无 ❌ 有限 ⚠️ 有限 中小型项目、传统 CSS
styled-components ✅ 局部 ✅ 有 ✅ 完全支持 ✅ TypeScript React 项目、动态主题
Emotion ✅ 局部 ✅ 有 ✅ 完全支持 ✅ TypeScript 高性能要求、SSR
Tailwind CSS ❌ 全局 ❌ 无 ⚠️ 有限 ❌ 无 快速开发、原型设计
CSS Variables ❌ 全局 ❌ 无 ✅ 运行时可变 ❌ 无 主题切换、动态配置

2. CSS Modules - 局部作用域

核心特性: 自动生成唯一的 class 名,避免全局污染
原理: 编译时将 .button 转换为 .button_abc123
/* Button.module.css */ .button { padding: 12px 24px; border-radius: 6px; font-weight: bold; } .primary { background: linear-gradient(135deg, #667eea, #764ba2); } .secondary { background: linear-gradient(135deg, #f093fb, #f5576c); } /* Button.jsx */ import styles from './Button.module.css'; function Button() { return ( <button className={`${styles.button} ${styles.primary}`}> Click Me </button> ); } // 编译后的 HTML: class="button_abc123 primary_def456"

3. CSS-in-JS - 动态样式

核心特性: 在 JavaScript 中编写 CSS,支持动态样式和主题
代表方案: styled-components、Emotion
/* styled-components 示例 */ import styled from 'styled-components'; const Button = styled.button` padding: ${props => props.size === 'large' ? '16px 32px' : '12px 24px'}; background: ${props => props.color || '#667eea'}; color: white; border: none; border-radius: 6px; font-weight: bold; cursor: pointer; &:hover { opacity: 0.9; transform: translateY(-2px); } `; /* 使用 */ <Button color="#667eea" size="large"> Click Me </Button>

4. Tailwind CSS - 原子化 CSS

核心特性: 提供大量原子化 class,快速构建 UI
优势: 开发速度快、文件体积小(按需生成)、设计系统一致
/* Tailwind CSS 示例 */ <button class="px-4 py-2 bg-blue-500 text-white rounded font-bold shadow hover:bg-blue-600 transition"> Click Me </button> /* tailwind.config.js */ module.exports = { content: ['./src/**/*.{js,jsx,ts,tsx}'], theme: { extend: { colors: { brand: '#667eea' }, spacing: { '72': '18rem' } } }, plugins: [] }; /* 使用自定义类 */ <div class="bg-brand p-72"></div>

5. CSS Variables - 原生动态样式

核心特性: CSS 原生支持,运行时可修改,无需编译
最佳场景: 主题切换、动态配置
16px
8px
/* 定义 CSS 变量 */ :root { --color-primary: #667eea; --color-secondary: #764ba2; --spacing: 16px; --radius: 8px; } /* 使用变量 */ .button { padding: var(--spacing); background: linear-gradient(135deg, var(--color-primary), var(--color-secondary)); border-radius: var(--radius); } /* JavaScript 动态修改 */ document.documentElement.style.setProperty('--color-primary', '#ff5500'); /* 响应式变量 */ @media (max-width: 768px) { :root { --spacing: 12px; } }

6. 各方案优缺点详解

CSS Modules

优点:

  • 局部作用域,避免冲突
  • 学习成本低
  • 无运行时开销
  • 支持所有 CSS 预处理器

缺点:

  • 动态样式支持弱
  • 需要构建工具
  • TypeScript 支持有限

styled-components

优点:

  • 完美的动态样式支持
  • TypeScript 类型安全
  • 自动删除未使用样式
  • 主题系统强大

缺点:

  • 运行时性能开销
  • 包体积较大
  • SSR 配置复杂

Tailwind CSS

优点:

  • 开发速度极快
  • 设计系统一致
  • 最终文件体积小
  • 无运行时开销

缺点:

  • HTML 代码冗长
  • 学习曲线陡峭
  • 调试困难
  • 复杂交互支持弱

CSS Variables

优点:

  • 原生支持,无依赖
  • 运行时可修改
  • 性能最优
  • 响应式友好

缺点:

  • 无作用域隔离
  • IE 不支持
  • 无类型安全
  • 功能相对简单