TailwindCSS v4 迁移指南
· 1 min read
v4 的核心变化
TailwindCSS v4 是一个重大更新,核心思路从 JS 配置转向 CSS-first 配置。
1. 安装方式
# v3 (旧)
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init
# v4 (新)
npm install tailwindcss @tailwindcss/vite @astrojs/tailwind2. 入口文件
/* v3 — tailwind directives */
@tailwind base;
@tailwind components;
@tailwind utilities;
/* v4 — single CSS import */
@import "tailwindcss";3. 主题配置
/* v4 — 在 CSS 中用 @theme 定义 */
@theme {
--color-primary: #3b82f6;
--color-accent: #8b5cf6;
--font-sans: "Inter", sans-serif;
}// v3 — 在 JS 中配置
module.exports = {
theme: {
extend: {
colors: { primary: "#3b82f6" },
},
},
};4. 暗色模式
/* v4 — 类名切类暗色模式 */
@custom-variant dark (&:where(.dark, .dark *));v3 需要在 tailwind.config.js 里设置 darkMode: "class"。
迁移检查清单
- 移除
postcss.config.js和tailwind.config.js - 用
@import "tailwindcss"替换@tailwinddirectives - 用
@theme {}替换 JS 配置 - 用
@custom-variant dark配置暗色模式 - 升级
@astrojs/tailwind到 v6
注意事项
⚠️ v4 的
@apply行为略有不同。如果遇到@apply不生效的问题,检查类名是否正确导入。
v4 还内置了 CSS 嵌套,不再需要 postcss-nesting:
.card {
background: var(--color-bg);
&:hover {
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
& .title {
font-weight: bold;
}
}迁移后构建速度提升约 40%,完整的 CSS 文件体积也缩小了。