Tailwind CSS 4.0 迁移实录
Tailwind 4.0 发布了,主打”更小、更快、更强”。第一时间试了,记录迁移过程。
主要变化
| 变化项 | 3.x | 4.0 |
|---|---|---|
| 引入方式 | PostCSS 插件 | Vite/Webpack 插件 |
| 配置文件 | tailwind.config.js | CSS 内配置 |
| JIT | 可选 | 默认开启 |
| 颜色系统 | 固定调色板 | 动态生成 |
| 暗色模式 | dark: 前缀 | 更灵活的变体 |
安装方式变了
以前 (3.x)
npm install tailwindcss postcss autoprefixer
npx tailwindcss init -p
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
现在 (4.0)
npm install @tailwindcss/vite
// vite.config.js
import tailwindcss from '@tailwindcss/vite';
export default {
plugins: [tailwindcss()],
};
配置更简洁了。
CSS 内配置
不再需要 tailwind.config.js,配置写在 CSS 里:
/* styles.css */
@import "tailwindcss";
@theme {
--color-primary: #3b82f6;
--color-secondary: #64748b;
--font-display: "Inter", sans-serif;
--breakpoint-xs: 375px;
}
然后在组件里直接用:
<button class="bg-primary text-white font-display">按钮</button>
迁移踩坑
1. 类名变化
有些类名改了:
- bg-opacity-50
- text-opacity-80
+ bg-blue-500/50
+ text-gray-900/80
颜色透明度语法更简洁了。
2. 配置迁移
// 3.x tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
brand: '#ff6600',
},
},
},
};
// 4.0 styles.css
@theme {
--color-brand: #ff6600;
}
花了点时间把配置迁移过去。
3. 插件兼容性
部分插件还没适配 4.0,比如 @tailwindcss/typography。用了兼容模式:
@config "./tailwind.config.js";
性能对比
迁移前后对比:
| 指标 | 3.x | 4.0 | 变化 |
|---|---|---|---|
| 开发构建速度 | 2.1s | 1.3s | -38% |
| 生产 CSS 体积 | 42KB | 38KB | -10% |
| HMR 速度 | 180ms | 45ms | -75% |
HMR 提升最明显,开发体验好了很多。
新特性体验
容器查询
<div class="@container">
<div class="@lg:grid-cols-2 @xl:grid-cols-3">
<!-- 根据容器宽度,不是视口宽度 -->
</div>
</div>
终于原生支持了,不用再装插件。
颜色函数
@theme {
--color-base: #1e293b;
}
/* 自动生成变体 */
.text-base-50 /* 最浅 */
.text-base-100
.text-base-200
/* ... */
.text-base-950 /* 最深 */
不用手动定义一堆颜色了。
更好的暗色模式
<div class="bg-white dark:bg-slate-900">
<!-- 以前 -->
</div>
<div class="bg-white [&:where(.dark_)]:bg-slate-900">
<!-- 现在,更灵活 -->
</div>
兼容性
| 浏览器 | 支持情况 |
|---|---|
| Chrome 111+ | 完全支持 |
| Firefox 128+ | 完全支持 |
| Safari 16.4+ | 完全支持 |
| 旧浏览器 | 部分特性降级 |
如果你的项目要兼容老浏览器,建议等一段时间再升级。
迁移建议
- 新项目直接用 4.0
- 老项目先用兼容模式,逐步迁移
- 检查插件兼容性
- 跑一遍视觉回归测试
我们项目迁移花了两天,主要是配置迁移和测试。
总结
Tailwind 4.0 是个大更新,配置方式变了,但核心类名兼容。性能提升明显,值得升级。
建议等生态成熟一点再大规模迁移,现在有些插件还在适配中。
对了,官方迁移指南写得很详细:https://tailwindcss.com/docs/upgrade-guide