Tailwind CSS 性能优化 #

JIT 编译器 #

工作原理 #

Tailwind CSS 使用即时编译器(JIT),只生成实际使用的 CSS:

text
扫描文件 → 查找类名 → 生成 CSS → 输出

优势 #

  • 极小的文件大小:只包含使用的样式
  • 任意值支持:可以使用任意值如 bg-[#1da1f2]
  • 更快的开发体验:无需等待完整编译
  • 所有变体开箱即用:无需配置变体

生产构建 #

基本构建 #

bash
# 开发模式
npx tailwindcss -i ./src/input.css -o ./dist/output.css --watch

# 生产构建
npx tailwindcss -i ./src/input.css -o ./dist/output.css --minify

package.json 脚本 #

json
{
  "scripts": {
    "dev": "tailwindcss -i ./src/input.css -o ./dist/output.css --watch",
    "build": "tailwindcss -i ./src/input.css -o ./dist/output.css --minify"
  }
}

内容配置 #

正确配置 content #

javascript
// tailwind.config.js
module.exports = {
  content: [
    './src/**/*.{html,js,ts,jsx,tsx}',
    './pages/**/*.{html,js}',
    './components/**/*.{html,js}',
  ],
}

避免过度扫描 #

javascript
// 不推荐:扫描所有文件
content: ['./**/*'],

// 推荐:精确指定路径
content: [
  './src/**/*.{html,js,ts,jsx,tsx}',
  './pages/**/*.{html,js}',
],

Safelist #

使用场景 #

当某些类名是动态生成的,需要确保它们被包含:

javascript
module.exports = {
  safelist: [
    // 确保这些类始终存在
    'bg-blue-500',
    'text-center',
    
    // 使用模式匹配
    {
      pattern: /bg-(red|green|blue)-(100|200|300)/,
    },
    
    // 匹配所有颜色
    {
      pattern: /text-(red|blue|green)-(500|600|700)/,
      variants: ['hover', 'focus'],
    },
  ],
}

动态类名问题 #

html
<!-- 不推荐:动态拼接类名 -->
<div class="text-{{ color }}-500">

<!-- 推荐:完整类名或使用 safelist -->
<div :class="{
  'text-red-500': color === 'red',
  'text-blue-500': color === 'blue',
  'text-green-500': color === 'green',
}">

CSS 压缩 #

使用 cssnano #

bash
npm install cssnano --save-dev
javascript
// postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
    ...(process.env.NODE_ENV === 'production' ? { cssnano: {} } : {}),
  },
}

压缩效果 #

css
/* 开发模式 */
.bg-blue-500 {
  --tw-bg-opacity: 1;
  background-color: rgb(59 130 246 / var(--tw-bg-opacity));
}

/* 生产模式 */
.bg-blue-500{--tw-bg-opacity:1;background-color:rgb(59 130 246/var(--tw-bg-opacity))}

移除未使用的样式 #

PurgeCSS(旧版本) #

javascript
// tailwind.config.js (v2.x)
module.exports = {
  purge: [
    './src/**/*.html',
    './src/**/*.js',
  ],
}

content 配置(新版本) #

javascript
// tailwind.config.js (v3.x+)
module.exports = {
  content: [
    './src/**/*.html',
    './src/**/*.js',
  ],
}

优化策略 #

1. 避免重复类名 #

html
<!-- 不推荐:重复相同的类名 -->
<div class="bg-white rounded-lg shadow-md p-6">
  <div class="bg-white rounded-lg shadow-md p-6">
    内容
  </div>
</div>

<!-- 推荐:提取组件 -->
<div class="card">
  <div class="card">
    内容
  </div>
</div>

2. 使用组件抽象 #

jsx
// React 组件
function Card({ children }) {
  return (
    <div className="bg-white rounded-lg shadow-md p-6">
      {children}
    </div>
  )
}

3. 合理使用 @apply #

css
/* 不推荐:过度使用 @apply */
.card {
  @apply bg-white rounded-lg shadow-md p-6 m-4 border border-gray-200;
}

/* 推荐:保持简洁 */
.card {
  @apply bg-white rounded-lg shadow-md;
  padding: 1.5rem;
}

4. 减少任意值 #

html
<!-- 不推荐:大量使用任意值 -->
<div class="bg-[#3b82f6] text-[14px] p-[16px] m-[8px]">

<!-- 推荐:使用预定义值 -->
<div class="bg-blue-500 text-sm p-4 m-2">

文件大小对比 #

开发模式 #

text
开发模式(未压缩):~3000KB

生产模式 #

text
生产模式(压缩后):~10-50KB(取决于使用的类)

检查文件大小 #

使用 tailwindcss CLI #

bash
npx tailwindcss -i ./src/input.css -o ./dist/output.css --minify

使用 bundlephobia #

bash
npx bundlephobia tailwindcss

性能最佳实践 #

1. 正确配置 content #

javascript
module.exports = {
  content: [
    // 精确指定路径
    './src/**/*.{html,js,ts,jsx,tsx}',
    
    // 包含组件库
    './node_modules/my-ui-library/**/*.{js,ts}',
  ],
}

2. 使用 JIT 模式 #

javascript
// 默认启用 JIT
module.exports = {
  // 无需额外配置
}

3. 避免动态类名 #

html
<!-- 不推荐 -->
<div class="text-{{ color }}-500">

<!-- 推荐 -->
<div :class="colorClass">
javascript
const colorClass = {
  red: 'text-red-500',
  blue: 'text-blue-500',
  green: 'text-green-500',
}[color]

4. 使用 CSS 变量 #

css
@layer base {
  :root {
    --color-primary: theme('colors.blue.500');
    --color-secondary: theme('colors.gray.500');
  }
}

5. 延迟加载 #

html
<!-- 延迟加载非关键 CSS -->
<link rel="preload" href="styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">

构建工具优化 #

Vite #

javascript
// vite.config.js
import { defineConfig } from 'vite'

export default defineConfig({
  build: {
    cssMinify: true,
  },
})

Webpack #

javascript
// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader',
          'postcss-loader',
        ],
      },
    ],
  },
}

Next.js #

javascript
// next.config.js
module.exports = {
  // 自动优化
}

监控性能 #

Lighthouse #

使用 Lighthouse 检查页面性能:

  1. 打开 Chrome DevTools
  2. 切换到 Lighthouse 标签
  3. 运行性能测试

WebPageTest #

使用 WebPageTest 测试页面加载性能:

  • 首次内容绘制(FCP)
  • 最大内容绘制(LCP)
  • 累积布局偏移(CLS)

下一步 #

恭喜你完成了 Tailwind CSS 的学习!继续学习 组件开发 了解实战应用!

最后更新:2026-03-28