tailwind-performance
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTailwind CSS - Performance Optimization
Tailwind CSS - 性能优化
Tailwind CSS includes powerful tools for optimizing your CSS for production, ensuring fast load times and minimal bundle sizes.
Tailwind CSS 内置强大工具,可针对生产环境优化CSS,确保加载速度快、包体积最小。
Key Concepts
核心概念
Just-In-Time (JIT) Mode
即时编译(JIT)模式
JIT mode (default since Tailwind 3.0) generates styles on-demand as you author your templates:
Benefits:
- Lightning-fast build times
- All variants enabled by default
- Arbitrary value support
- Smaller development builds
- No separate production build needed
javascript
// tailwind.config.js (JIT is default, no config needed)
module.exports = {
content: ['./src/**/*.{html,js,jsx,ts,tsx}'],
// JIT mode is automatic
}JIT模式(Tailwind 3.0起默认启用)会在你编写模板时按需生成样式:
优势:
- 极快的构建速度
- 默认启用所有变体
- 支持任意值
- 更小的开发构建包
- 无需单独的生产构建
javascript
// tailwind.config.js (JIT is default, no config needed)
module.exports = {
content: ['./src/**/*.{html,js,jsx,ts,tsx}'],
// JIT mode is automatic
}Content Configuration
内容路径配置
Proper content paths are critical for performance:
javascript
module.exports = {
content: [
'./src/**/*.{js,jsx,ts,tsx}',
'./pages/**/*.{js,jsx,ts,tsx}',
'./components/**/*.{js,jsx,ts,tsx}',
'./app/**/*.{js,jsx,ts,tsx}',
// Include any files that contain Tailwind classes
'./public/index.html',
],
}合理配置内容路径对性能至关重要:
javascript
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',
],
}Best Practices
最佳实践
1. Optimize Content Paths
1. 优化内容路径
Be specific to avoid scanning unnecessary files:
javascript
// Good: Specific paths
module.exports = {
content: [
'./src/**/*.{js,jsx,ts,tsx}',
'./components/**/*.{js,jsx,ts,tsx}',
],
}
// Bad: Too broad
module.exports = {
content: [
'./**/*.{js,jsx,ts,tsx}', // Scans node_modules!
],
}路径要具体,避免扫描不必要的文件:
javascript
// 推荐:路径具体
module.exports = {
content: [
'./src/**/*.{js,jsx,ts,tsx}',
'./components/**/*.{js,jsx,ts,tsx}',
],
}
// 不推荐:范围过宽
module.exports = {
content: [
'./**/*.{js,jsx,ts,tsx}', // 会扫描node_modules!
],
}2. Use Safelist for Dynamic Classes
2. 为动态类使用安全列表
When class names are constructed dynamically, use safelist:
javascript
module.exports = {
content: ['./src/**/*.{js,jsx,ts,tsx}'],
safelist: [
'bg-red-500',
'bg-green-500',
'bg-blue-500',
// Or use patterns
{
pattern: /bg-(red|green|blue)-(400|500|600)/,
variants: ['hover', 'focus'],
},
],
}当类名是动态生成时,使用安全列表:
javascript
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. Avoid String Concatenation
3. 避免字符串拼接
Don't construct class names dynamically:
jsx
// Bad: These classes won't be detected
<div className={`text-${size}`}>
<div className={`bg-${color}-500`}>
// Good: Use complete class names
<div className={size === 'large' ? 'text-lg' : 'text-sm'}>
<div className={color === 'red' ? 'bg-red-500' : 'bg-blue-500'}>
// Or use safelist for dynamic values不要动态拼接类名:
jsx
// 不推荐:这些类无法被检测到
<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. Minimize Custom CSS
4. 最小化自定义CSS
Rely on utilities to reduce overall CSS size:
css
/* Bad: Custom CSS that duplicates utilities */
.my-button {
background-color: #3b82f6;
color: white;
padding: 0.5rem 1rem;
border-radius: 0.375rem;
}
/* Good: Use utilities or @apply */
@layer components {
.my-button {
@apply bg-blue-500 text-white px-4 py-2 rounded-md;
}
}
/* Better: Component abstraction (no custom CSS) */依赖工具类来减少整体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. Enable CSS Minification
5. 启用CSS压缩
Ensure your build process minifies CSS:
javascript
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
...(process.env.NODE_ENV === 'production' ? { cssnano: {} } : {})
},
}确保构建流程中包含CSS压缩:
javascript
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
...(process.env.NODE_ENV === 'production' ? { cssnano: {} } : {})
},
}6. Use CSS Variables Strategically
6. 合理使用CSS变量
Combine Tailwind with CSS variables for theme switching without bloat:
css
:root {
--color-primary: 59 130 246; /* RGB */
}
[data-theme='dark'] {
--color-primary: 96 165 250;
}javascript
// tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
primary: 'rgb(var(--color-primary) / <alpha-value>)',
},
},
},
}结合Tailwind与CSS变量实现主题切换,避免冗余代码:
css
:root {
--color-primary: 59 130 246; /* RGB */
}
[data-theme='dark'] {
--color-primary: 96 165 250;
}javascript
// tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
primary: 'rgb(var(--color-primary) / <alpha-value>)',
},
},
},
}Build Optimization
构建优化
Vite Configuration
Vite配置
javascript
// vite.config.js
import { defineConfig } from 'vite'
export default defineConfig({
css: {
postcss: './postcss.config.js',
},
build: {
cssMinify: 'esbuild', // Fast CSS minification
rollupOptions: {
output: {
manualChunks: {
// Separate vendor chunks
vendor: ['react', 'react-dom'],
},
},
},
},
})javascript
// 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 Configuration
Next.js配置
javascript
// next.config.js
module.exports = {
experimental: {
optimizeCss: true, // Enable CSS optimization
},
// Next.js automatically optimizes Tailwind
}javascript
// next.config.js
module.exports = {
experimental: {
optimizeCss: true, // 启用CSS优化
},
// Next.js会自动优化Tailwind
}Webpack Configuration
Webpack配置
javascript
// 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',
}),
],
}javascript
// 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',
}),
],
}Performance Patterns
性能优化模式
1. Code Splitting
1. 代码拆分
Split CSS by route or component:
javascript
// Using dynamic imports
const HeavyComponent = lazy(() => import('./HeavyComponent'))
// Tailwind classes in HeavyComponent will be in a separate chunk按路由或组件拆分CSS:
javascript
// 使用动态导入
const HeavyComponent = lazy(() => import('./HeavyComponent'))
// HeavyComponent中的Tailwind类会被打包到单独的代码块中2. Critical CSS
2. 关键CSS提取
Extract critical CSS for above-the-fold content:
html
<!DOCTYPE html>
<html>
<head>
<style>
/* Inline critical CSS */
.hero { /* ... */ }
.nav { /* ... */ }
</style>
<!-- Load full CSS async -->
<link rel="preload" href="/styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="/styles.css"></noscript>
</head>提取首屏内容的关键CSS:
html
<!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. Lazy Load Non-Critical Styles
3. 懒加载非关键样式
javascript
// Load additional styles when needed
if (shouldLoadDarkMode) {
import('./dark-mode.css')
}javascript
// 在需要时加载额外样式
if (shouldLoadDarkMode) {
import('./dark-mode.css')
}4. Font Optimization
4. 字体优化
javascript
// tailwind.config.js
module.exports = {
theme: {
extend: {
fontFamily: {
sans: [
'Inter var',
'system-ui',
'-apple-system',
'BlinkMacSystemFont',
'"Segoe UI"',
'Roboto',
'sans-serif',
],
},
},
},
}css
/* Use font-display for better loading */
@font-face {
font-family: 'Inter var';
font-style: normal;
font-weight: 100 900;
font-display: swap; /* Prevent invisible text */
src: url('/fonts/inter-var.woff2') format('woff2');
}javascript
// tailwind.config.js
module.exports = {
theme: {
extend: {
fontFamily: {
sans: [
'Inter var',
'system-ui',
'-apple-system',
'BlinkMacSystemFont',
'"Segoe UI"',
'Roboto',
'sans-serif',
],
},
},
},
}css
/* 使用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');
}Monitoring Performance
性能监控
Bundle Size Analysis
包体积分析
bash
undefinedbash
undefinedAnalyze CSS bundle size
分析CSS包体积
npx tailwindcss -i ./src/input.css -o ./dist/output.css --minify
npx tailwindcss -i ./src/input.css -o ./dist/output.css --minify
Check file size
查看文件大小
ls -lh dist/output.css
ls -lh dist/output.css
Detailed analysis with webpack-bundle-analyzer
使用webpack-bundle-analyzer进行详细分析
npm install --save-dev webpack-bundle-analyzer
undefinednpm install --save-dev webpack-bundle-analyzer
undefinedLighthouse Metrics
Lighthouse指标
Target metrics:
- First Contentful Paint (FCP): < 1.8s
- Largest Contentful Paint (LCP): < 2.5s
- Cumulative Layout Shift (CLS): < 0.1
- CSS Bundle Size: < 50KB (gzipped)
目标指标:
- 首次内容绘制(FCP):< 1.8秒
- 最大内容绘制(LCP):< 2.5秒
- 累积布局偏移(CLS):< 0.1
- CSS包体积:< 50KB(gzip压缩后)
Performance Checklist
性能检查清单
markdown
✅ Content paths are specific and optimized
✅ JIT mode is enabled (default in Tailwind 3+)
✅ CSS is minified in production
✅ Unused styles are purged
✅ Dynamic classes use safelist
✅ Critical CSS is inlined
✅ Fonts use font-display: swap
✅ CSS is code-split by route/chunk
✅ Gzip/Brotli compression enabled
✅ CSS file has content hash for cachingmarkdown
✅ 内容路径已优化且具体
✅ JIT模式已启用(Tailwind 3+默认启用)
✅ 生产环境下CSS已压缩
✅ 未使用的样式已被清除
✅ 动态类已使用安全列表
✅ 关键CSS已内联
✅ 字体使用font-display: swap
✅ CSS已按路由/代码块拆分
✅ Gzip/Brotli压缩已启用
✅ CSS文件添加内容哈希用于缓存Examples
示例
Production Build Script
生产环境构建脚本
json
// 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"
}
}json
// 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"
}
}Optimized Configuration
优化后的配置
javascript
// tailwind.config.js
module.exports = {
content: {
files: [
'./src/**/*.{js,jsx,ts,tsx}',
'./components/**/*.{js,jsx,ts,tsx}',
],
// Only in dev: watch for changes
relative: process.env.NODE_ENV === 'development',
},
theme: {
extend: {
// Only extend what you need
colors: {
primary: 'rgb(var(--color-primary) / <alpha-value>)',
},
},
},
plugins: [
// Only include plugins you use
require('@tailwindcss/forms'),
],
// Disable unused variants
corePlugins: {
// Disable unused features
preflight: true,
// Only enable what you need
},
}javascript
// 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 vs Bundle Comparison
CDN与本地打包对比
html
<!-- Bad: CDN (3.5MB+, not optimized) -->
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@3/dist/tailwind.min.css" rel="stylesheet">
<!-- Good: Bundled & optimized (typically 5-20KB gzipped) -->
<link href="/dist/styles.css" rel="stylesheet">html
<!-- 不推荐:CDN版本(3.5MB+,未优化) -->
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@3/dist/tailwind.min.css" rel="stylesheet">
<!-- 推荐:本地打包并优化(gzip压缩后通常5-20KB) -->
<link href="/dist/styles.css" rel="stylesheet">Common Pitfalls
常见陷阱
❌ Using CDN in Production
❌ 生产环境使用CDN版本
html
<!-- Never do this in production -->
<script src="https://cdn.tailwindcss.com"></script>The CDN build is 3.5MB+ and includes all utilities. Always use a build process.
html
<!-- 生产环境绝不要这样做 -->
<script src="https://cdn.tailwindcss.com"></script>CDN版本体积达3.5MB+,包含所有工具类。务必使用构建流程生成的文件。
❌ Overly Broad Content Paths
❌ 内容路径范围过宽
javascript
// Bad: Scans everything including node_modules
content: ['./**/*.html']
// Good: Specific to your source files
content: ['./src/**/*.{html,js,jsx,ts,tsx}']javascript
// 不推荐:扫描所有文件包括node_modules
content: ['./**/*.html']
// 推荐:仅指定源码文件
content: ['./src/**/*.{html,js,jsx,ts,tsx}']❌ Not Using Safelist for Dynamic Classes
❌ 动态类未使用安全列表
jsx
// Bad: Class won't be included in build
const colors = ['red', 'blue', 'green']
<div className={`bg-${colors[index]}-500`} />
// Good: Use safelist or conditional classesjsx
// 不推荐:类不会被包含在构建包中
const colors = ['red', 'blue', 'green']
<div className={`bg-${colors[index]}-500`} />
// 推荐:使用安全列表或条件类名❌ Importing Full Tailwind in Components
❌ 在组件中导入完整Tailwind
javascript
// Bad: Imports all of Tailwind
import 'tailwindcss/tailwind.css'
// Good: Import only what you built
import './styles.css'javascript
// 不推荐:导入完整的Tailwind
import 'tailwindcss/tailwind.css'
// 推荐:仅导入构建后的样式
import './styles.css'Anti-Patterns
反模式
❌ Don't Disable Purge in Production
❌ 生产环境禁用样式清除
javascript
// Bad: Never do this
module.exports = {
content: [], // Empty = no purging!
}javascript
// 不推荐:绝不要这样做
module.exports = {
content: [], // 空数组 = 不清除样式!
}❌ Don't Use @apply Excessively
❌ 过度使用@apply
css
/* Bad: Defeating the purpose of utilities */
.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; }
/* ...hundreds of components */
/* This negates Tailwind's optimization benefits */css
/* 不推荐:违背工具类的设计初衷 */
.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的优化优势 */❌ Don't Ignore Build Warnings
❌ 忽略构建警告
bash
undefinedbash
undefinedPay attention to warnings like:
注意如下警告:
"The content option in your Tailwind CSS configuration is missing or empty"
"The content option in your Tailwind CSS configuration is missing or empty"
"No utility classes were detected in your source files"
"No utility classes were detected in your source files"
undefinedundefinedRelated Skills
相关技能
- tailwind-configuration: Customizing Tailwind config and theme
- tailwind-utility-classes: Using Tailwind's utility classes effectively
- tailwind-responsive-design: Building responsive designs efficiently
- tailwind-configuration:自定义Tailwind配置与主题
- tailwind-utility-classes:高效使用Tailwind工具类
- tailwind-responsive-design:高效构建响应式设计