name: tailwind-performance user-invocable: false description: 当优化Tailwind CSS的生产环境时使用,以减少包大小并提高性能。涵盖PurgeCSS、JIT模式和构建优化。 allowed-tools:
- 读取
- 写入
- 编辑
- Bash
- Grep
- Glob
Tailwind CSS - 性能优化
Tailwind CSS包含强大的工具,用于优化CSS以生产环境,确保快速加载时间和最小的包大小。
关键概念
即时(JIT)模式
JIT模式(自Tailwind 3.0起默认启用)在您编写模板时按需生成样式:
优点:
- 极快的构建时间
- 默认启用所有变体
- 支持任意值
- 较小的开发构建
- 无需单独的生产构建
// tailwind.config.js(JIT是默认的,无需配置)
module.exports = {
content: ['./src/**/*.{html,js,jsx,ts,tsx}'],
// JIT模式自动启用
}
内容配置
正确的内容路径对性能至关重要:
module.exports = {
content: [
'./src/**/*.{js,jsx,ts,tsx}',
'./pages/**/*.{js,jsx,ts,tsx}',
'./components/**/*.{js,jsx,ts,tsx}',
'./app/**/*.{js,jsx,ts,tsx}',
// 包含任何包含Tailwind类的文件
'./public/index.html',
],
}
最佳实践
1. 优化内容路径
具体指定以避免扫描不必要的文件:
// 好:具体路径
module.exports = {
content: [
'./src/**/*.{js,jsx,ts,tsx}',
'./components/**/*.{js,jsx,ts,tsx}',
],
}
// 坏:太宽泛
module.exports = {
content: [
'./**/*.{js,jsx,ts,tsx}', // 扫描node_modules!
],
}
2. 使用安全列表处理动态类
当类名动态构造时,使用安全列表:
module.exports = {
content: ['./src/**/*.{js,jsx,ts,tsx}'],
safelist: [
'bg-red-500',
'bg-green-500',
'bg-blue-500',
// 或使用模式
{
pattern: /bg-(red|green|blue)-(400|500|600)/,
variants: ['hover', 'focus'],
},
],
}
3. 避免字符串拼接
不要动态构造类名:
// 坏:这些类不会被检测到
<div className={`text-${size}`}>
<div className={`bg-${color}-500`}>
// 好:使用完整类名
<div className={size === 'large' ? 'text-lg' : 'text-sm'}>
<div className={color === 'red' ? 'bg-red-500' : 'bg-blue-500'}>
// 或使用安全列表处理动态值
4. 最小化自定义CSS
依赖实用程序来减少整体CSS大小:
/* 坏:自定义CSS重复了实用程序 */
.my-button {
background-color: #3b82f6;
color: white;
padding: 0.5rem 1rem;
border-radius: 0.375rem;
}
/* 好:使用实用程序或@apply */
@layer components {
.my-button {
@apply bg-blue-500 text-white px-4 py-2 rounded-md;
}
}
/* 更好:组件抽象(无自定义CSS) */
5. 启用CSS压缩
确保构建过程压缩CSS:
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
...(process.env.NODE_ENV === 'production' ? { cssnano: {} } : {})
},
}
6. 策略性地使用CSS变量
结合Tailwind与CSS变量以在不增加冗余的情况下切换主题:
:root {
--color-primary: 59 130 246; /* RGB */
}
[data-theme='dark'] {
--color-primary: 96 165 250;
}
// tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
primary: 'rgb(var(--color-primary) / <alpha-value>)',
},
},
},
}
构建优化
Vite配置
// vite.config.js
import { defineConfig } from 'vite'
export default defineConfig({
css: {
postcss: './postcss.config.js',
},
build: {
cssMinify: 'esbuild', // 快速CSS压缩
rollupOptions: {
output: {
manualChunks: {
// 分离供应商块
vendor: ['react', 'react-dom'],
},
},
},
},
})
Next.js配置
// next.config.js
module.exports = {
experimental: {
optimizeCss: true, // 启用CSS优化
},
// Next.js自动优化Tailwind
}
Webpack配置
// webpack.config.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
module.exports = {
optimization: {
minimizer: [
new CssMinimizerPlugin(),
],
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css',
}),
]
}
性能模式
1. 代码分割
按路由或组件分割CSS:
// 使用动态导入
const HeavyComponent = lazy(() => import('./HeavyComponent'))
// HeavyComponent中的Tailwind类将在一个单独的块中
2. 关键CSS
提取首屏内容的关键CSS:
<!DOCTYPE html>
<html>
<head>
<style>
/* 内联关键CSS */
.hero { /* ... */ }
.nav { /* ... */ }
</style>
<!-- 异步加载完整CSS -->
<link rel="preload" href="/styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="/styles.css"></noscript>
</head>
3. 懒加载非关键样式
// 需要时加载附加样式
if (shouldLoadDarkMode) {
import('./dark-mode.css')
}
4. 字体优化
// tailwind.config.js
module.exports = {
theme: {
extend: {
fontFamily: {
sans: [
'Inter var',
'system-ui',
'-apple-system',
'BlinkMacSystemFont',
'"Segoe UI"',
'Roboto',
'sans-serif',
],
},
},
},
}
/* 使用font-display以获得更好的加载 */
@font-face {
font-family: 'Inter var';
font-style: normal;
font-weight: 100 900;
font-display: swap; /* 防止不可见文本 */
src: url('/fonts/inter-var.woff2') format('woff2');
}
监控性能
包大小分析
# 分析CSS包大小
npx tailwindcss -i ./src/input.css -o ./dist/output.css --minify
# 检查文件大小
ls -lh dist/output.css
# 使用webpack-bundle-analyzer进行详细分析
npm install --save-dev webpack-bundle-analyzer
Lighthouse指标
目标指标:
- 首次内容绘制(FCP):< 1.8秒
- 最大内容绘制(LCP):< 2.5秒
- 累积布局偏移(CLS):< 0.1
- CSS包大小:< 50KB(gzip压缩后)
性能检查清单
✅ 内容路径具体且优化
✅ JIT模式已启用(Tailwind 3+中默认)
✅ 生产环境中CSS已压缩
✅ 未使用的样式已清理
✅ 动态类使用安全列表
✅ 关键CSS已内联
✅ 字体使用font-display: swap
✅ CSS按路由/块代码分割
✅ 启用Gzip/Brotli压缩
✅ CSS文件有内容哈希以缓存
示例
生产构建脚本
// package.json
{
"scripts": {
"dev": "vite",
"build": "vite build",
"build:css": "tailwindcss -i ./src/input.css -o ./dist/output.css --minify",
"analyze": "npm run build && webpack-bundle-analyzer dist/stats.json"
}
}
优化配置
// tailwind.config.js
module.exports = {
content: {
files: [
'./src/**/*.{js,jsx,ts,tsx}',
'./components/**/*.{js,jsx,ts,tsx}',
],
// 仅开发环境:监视更改
relative: process.env.NODE_ENV === 'development',
},
theme: {
extend: {
// 仅扩展所需内容
colors: {
primary: 'rgb(var(--color-primary) / <alpha-value>)',
},
},
},
plugins: [
// 仅包含您使用的插件
require('@tailwindcss/forms'),
],
// 禁用未使用的变体
corePlugins: {
// 禁用未使用的功能
preflight: true,
// 仅启用所需内容
},
}
CDN与打包对比
<!-- 坏:CDN(3.5MB+,未优化) -->
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@3/dist/tailwind.min.css" rel="stylesheet">
<!-- 好:打包且优化(通常5-20KB gzip压缩后) -->
<link href="/dist/styles.css" rel="stylesheet">
常见陷阱
❌ 在生产环境中使用CDN
<!-- 生产环境中切勿这样做 -->
<script src="https://cdn.tailwindcss.com"></script>
CDN构建大小为3.5MB+,并包含所有实用程序。始终使用构建过程。
❌ 内容路径过于宽泛
// 坏:扫描所有内容包括node_modules
content: ['./**/*.html']
// 好:具体到您的源文件
content: ['./src/**/*.{html,js,jsx,ts,tsx}']
❌ 未对动态类使用安全列表
// 坏:类不会包含在构建中
const colors = ['red', 'blue', 'green']
<div className={`bg-${colors[index]}-500`} />
// 好:使用安全列表或条件类
❌ 在组件中导入完整Tailwind
// 坏:导入所有Tailwind
import 'tailwindcss/tailwind.css'
// 好:仅导入您构建的
import './styles.css'
反模式
❌ 不要在生成环境中禁用清理
// 坏:切勿这样做
module.exports = {
content: [], // 空 = 无清理!
}
❌ 不要过度使用@apply
/* 坏:违背了实用程序的初衷 */
.btn { @apply px-4 py-2 bg-blue-500 text-white rounded; }
.card { @apply p-6 bg-white shadow-lg rounded-lg; }
.header { @apply flex items-center justify-between p-4; }
/* ...数百个组件 */
/* 这否定了Tailwind的优化优势 */
❌ 不要忽略构建警告
# 注意警告,例如:
# "您的Tailwind CSS配置中的content选项缺失或为空"
# "在您的源文件中未检测到实用程序类"
相关技能
- tailwind-configuration:自定义Tailwind配置和主题
- tailwind-utility-classes:有效使用Tailwind的实用程序类
- tailwind-responsive-design:高效构建响应式设计