Chapter 10

性能优化与生产

Oxide 引擎 5x 加速、tree-shaking 原理、CSS 体积控制,以及从其他方案的迁移指南

1. v4 构建速度:Oxide 引擎

Tailwind CSS v4 引入了全新的 Oxide 引擎,这是性能提升的核心。Oxide 由 Rust 编写(使用 Lightning CSS 作为底层),相比 v3 的纯 JavaScript 实现,性能大幅提升。

场景v3 速度v4 速度提升
全量构建(cold build)~3500ms~500ms~7x
增量构建(hot rebuild)~100ms~2ms~50x
大型项目全量构建~22000ms~4000ms~5x
ℹ️

Lightning CSS:一个用 Rust 编写的超快 CSS 解析器、转换器和压缩器。v4 用它替代了之前的 PostCSS 处理管道。Lightning CSS 同时处理浏览器兼容性前缀(autoprefixer)、CSS 压缩和 Tailwind 的工具类生成,一步到位。

2. Tree-shaking 原理

Tailwind 的 tree-shaking 机制不同于 JavaScript tree-shaking——它通过静态内容扫描实现:

  1. 扫描阶段:Tailwind 扫描所有配置的源文件(HTML、JSX、Vue 等),用正则提取所有可能是工具类的字符串(包括 class=""、className=""、:class="" 等属性中的内容)
  2. 匹配阶段:将扫描到的字符串与已知的工具类规则匹配,识别出实际使用的类(如 flexp-4text-cyan-500
  3. 生成阶段:只为匹配到的类生成对应的 CSS 规则,其余数千个可能的工具类不生成
  4. 输出结果:生产 CSS 通常仅 5-15KB(gzip 后),相比完整 CSS 文件(原始 ~4MB)极小
/* v4 自动扫描的文件类型(无需手动配置 content)*/
/* Vite 插件模式下自动检测 Vite 的模块图 */
/* PostCSS 模式下扫描与 CSS 文件相关的源文件 */

/* 如需手动指定额外扫描路径(v4 通过 @source 指令)*/
@import "tailwindcss";
@source "../templates/**/*.html";    /* 扫描 Django/Jinja2 模板 */
@source "../../packages/ui/src";      /* 扫描 monorepo 其他包 */

3. CSS 体积优化

生产构建配置(Vite)

// vite.config.ts
import { defineConfig } from 'vite'
import tailwindcss from '@tailwindcss/vite'

export default defineConfig({
  plugins: [tailwindcss()],

  build: {
    // CSS 代码分割(每个异步 chunk 有独立 CSS)
    cssCodeSplit: true,

    // 内联小于 4kb 的 CSS 资源(减少请求数)
    assetsInlineLimit: 4096,

    rollupOptions: {
      output: {
        // 自定义 CSS 文件名(便于缓存控制)
        assetFileNames: 'assets/[name]-[hash][extname]',
      }
    }
  }
})

减小 CSS 体积的实践技巧

/* 1. 用 @theme 的 initial 关键字移除不需要的默认 token */
@import "tailwindcss";

@theme {
  /* 移除所有默认颜色,只保留自定义颜色 */
  --color-*: initial;
  --color-brand: #06B6D4;
  --color-white: white;
  --color-black: black;
  --color-gray-50: #f9fafb;
  /* ... 只添加实际需要的颜色 */
}

4. Tailwind + CSS Modules 混用

虽然 utility-first 是 Tailwind 的推荐方式,但某些场景(如复杂的动画、第三方库集成)确实需要传统 CSS。混用策略:

/* Button.module.css —— 只写 Tailwind 难以表达的样式 */
.ripple {
  position: relative;
  overflow: hidden;
}
.ripple::after {
  content: '';
  position: absolute;
  width: 100%; height: 100%;
  background: radial-gradient(circle, rgba(255,255,255,0.3) 10%, transparent 10%);
  background-position: 50%;
  transform: scale(10); opacity: 0;
  transition: transform 0.5s, opacity 0.8s;
}
.ripple:active::after {
  transform: scale(0); opacity: 0.3;
  transition: 0s;
}
// Button.tsx
import styles from './Button.module.css'
import { cn } from '@/utils/cn'

export function Button({ children, className }: ButtonProps) {
  return (
    <button
      // Tailwind 工具类 + CSS Module 的 ripple 类
      className={cn(
        'px-6 py-3 bg-cyan-500 text-white rounded-xl font-semibold',
        styles.ripple,  // CSS Module 类
        className
      )}
    >
      {children}
    </button>
  )
}

5. 从其他 CSS 方案迁移指南

从 v3 迁移到 v4

# 官方迁移工具(自动转换大多数变化)
npx @tailwindcss/upgrade@next

# 主要需要注意的手动变更:
# 1. 删除 tailwind.config.js,将配置迁移到 @theme {}
# 2. @tailwind base/components/utilities → @import "tailwindcss"
# 3. content 配置 → v4 自动扫描,或 @source 指令
# 4. 部分颜色名变化(如 shadow-sm 默认颜色)

从 styled-components / Emotion 迁移

// ── Before: styled-components ──
const Card = styled.div`
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
  &:hover { box-shadow: 0 8px 25px rgba(0,0,0,0.15); }
`;

// ── After: Tailwind ──
function Card({ children }) {
  return (
    <div className="bg-white rounded-xl p-6 shadow-md hover:shadow-lg transition-shadow">
      {children}
    </div>
  )
}

从 Bootstrap 迁移

BootstrapTailwind 等效
.containermax-w-7xl mx-auto px-4
.row .col-md-6grid grid-cols-1 md:grid-cols-2 gap-4
.d-flex align-items-centerflex items-center
.btn btn-primarypx-4 py-2 bg-blue-600 text-white rounded
.text-mutedtext-gray-500
.mt-3mt-3(值含义不同,Bootstrap mt-3 = 1rem,Tailwind mt-3 = 0.75rem)

课程总结:Tailwind CSS v4 代表了 CSS 工具链的新方向——零配置文件、CSS-first 设计、Rust 驱动的极速构建。10 章内容覆盖了从入门到生产的完整链路。建议从一个真实小项目开始练习:安装 Tailwind v4 + Vite,做一个完整的登录页面,同时运用响应式、深色模式、交互状态和表单组件。动手是最快的学习路径。