Tailwind CSS 性能优化
v4 性能改进
Tailwind CSS v4 采用 Rust 完全重写的引擎:
| 指标 | v3 | v4 |
|---|---|---|
| 完整构建 | 基线 | 最高快 5 倍 |
| 增量构建 | 毫秒级 | 微秒级(快 100 倍以上) |
| 引擎 | JavaScript | Rust |
JIT(即时编译)
JIT 会在文件中发现类名时按需生成样式:扫描源文件中的类名;只生成你用到的 CSS;产出最小化、优化后的输出。
v4:始终启用 JIT
与 v3 不同,v4 中 JIT 始终启用,无需配置:
@import "tailwindcss";
/* JIT is automatic */
内容检测
v4 自动检测模板文件,无需 content 配置:
/* v4 - Works automatically */
@import "tailwindcss";
如果自动检测失效,可显式指定来源:
@import "tailwindcss";
@source "./src/**/*.{html,js,jsx,ts,tsx,vue,svelte}";
@source "./components/**/*.{js,jsx,ts,tsx}";
排除路径:
@source not "./src/legacy/**";
Tree Shaking
构建过程会移除未使用的 CSS:来源为全部可能的工具类(约 15MB 以上)→ 扫描查找用到的类名 → 输出仅包含用到的样式(通常约 10-50KB)。
生产构建:
# Vite - automatically optimized for production
npm run build
# PostCSS - ensure NODE_ENV is set
NODE_ENV=production npx postcss input.css -o output.css
动态类名
Tailwind 无法检测动态拼接的类名:
// BAD - Classes won't be generated
const color = 'blue'
className={`text-${color}-500`} // ❌ Not detected
const size = 'lg'
className={`text-${size}`} // ❌ Not detected
解决方案:
- 使用完整类名:
// GOOD - Full class names
const colorClasses = {
blue: 'text-blue-500',
red: 'text-red-500',
green: 'text-green-500',
}
className={colorClasses[color]} // ✓ Detected
- 使用 data 属性:
// GOOD - Style based on data attributes
<div data-color={color} className="data-[color=blue]:text-blue-500 data-[color=red]:text-red-500">
- Safelist 类名:
/* In your CSS for v4 */
@source inline("text-blue-500 text-red-500 text-green-500");
- CSS 变量:
@theme {
--color-dynamic: oklch(0.6 0.2 250);
}
<div class="text-[var(--color-dynamic)]">Dynamic color</div>
优化过渡
使用具体的过渡属性:
<!-- SLOW - Transitions all properties -->
<button class="transition-all duration-200">
<!-- FAST - Only transitions specific properties -->
<button class="transition-colors duration-200">
<button class="transition-transform duration-200">
<button class="transition-opacity duration-200">
GPU 加速属性,优先使用 transform 和 opacity 实现平滑动画:
<!-- GOOD - GPU accelerated -->
<div class="transform hover:scale-105 transition-transform">
<!-- GOOD - GPU accelerated -->
<div class="opacity-100 hover:opacity-80 transition-opacity">
<!-- SLOW - May cause repaints -->
<div class="left-0 hover:left-4 transition-all">
CSS 变量用法
优先使用原生变量。v4 中直接使用 CSS 变量而非 theme():
/* v3 - Uses theme() function */
.element {
color: theme(colors.blue.500);
}
/* v4 - Use CSS variables (faster) */
.element {
color: var(--color-blue-500);
}
静态主题值,针对性能关键路径:
@import "tailwindcss/theme.css" theme(static);
这会内联主题值,而非使用 CSS 变量。
构建优化
Vite 配置:
// vite.config.js
import tailwindcss from '@tailwindcss/vite'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [tailwindcss()],
build: {
// Minify CSS
cssMinify: 'lightningcss',
// Optimize chunks
rollupOptions: {
output: {
manualChunks: {
// Split vendor CSS if needed
}
}
}
}
})
PostCSS 配合 cssnano:
// postcss.config.mjs
export default {
plugins: {
'@tailwindcss/postcss': {},
cssnano: process.env.NODE_ENV === 'production' ? {} : false
}
}
减小包体积
- 避免未使用的插件:
/* Only load what you need */
@plugin "@tailwindcss/typography";
/* Don't load unused plugins */
- 限制调色板:
@theme {
/* Disable default colors */
--color-*: initial;
/* Define only needed colors */
--color-primary: oklch(0.6 0.2 250);
--color-secondary: oklch(0.7 0.15 180);
--color-gray-100: oklch(0.95 0 0);
--color-gray-900: oklch(0.15 0 0);
}
- 限制断点:
@theme {
/* Remove unused breakpoints */
--breakpoint-2xl: initial;
/* Keep only what you use */
--breakpoint-sm: 640px;
--breakpoint-md: 768px;
--breakpoint-lg: 1024px;
}
缓存策略
开发环境:v4 的增量构建本身已非常快,多数情况下无需额外缓存。
CI/CD(GitHub Actions 示例):
- name: Cache node_modules
uses: actions/cache@v4
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }}
- name: Build
run: npm run build
测量性能
构建耗时分析:
# Time your build
time npm run build
# Verbose output
DEBUG=tailwindcss:* npm run build
包分析:
# Install analyzer
npm install -D vite-bundle-analyzer
# Analyze bundle
npm run build -- --analyze
CSS 体积检查:
# Check output CSS size
ls -lh dist/assets/*.css
# Gzipped size
gzip -c dist/assets/main.css | wc -c
性能检查清单
开发环境:JIT 正常工作(样式即时更新);无关于大文件的控制台警告;热重载快速。
生产环境:已设置 NODE_ENV=production;CSS 已压缩;未使用的 CSS 已移除;无动态类名问题;CSS 体积合理(通常小于 50KB)。
常见问题
| 问题 | 解决方案 |
|---|---|
| CSS 输出过大 | 检查动态类名、safelist 问题 |
| 构建缓慢 | 确认使用 v4,检查文件 glob |
| 样式缺失 | 检查内容检测、类名 |
| 动画卡顿 | 使用 GPU 加速属性 |
CSS 懒加载
对于超大型应用,可考虑对 CSS 做代码分割:
// Dynamically import CSS for routes
const AdminPage = lazy(() =>
import('./admin.css').then(() => import('./AdminPage'))
)
最佳实践总结
- 让 JIT 发挥作用——不要不必要地 safelist
- 使用完整类名——避免动态拼接
- 使用具体的过渡属性——不要用 transition-all
- 使用 GPU 属性——优先 transform 和 opacity
- 精简主题——只定义用到的内容
- 生产构建——始终使用生产模式
- 测量——检查实际的 CSS 体积