🏠 My Blog

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/tailwind

2. 入口文件

/* 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.jstailwind.config.js
  • @import "tailwindcss" 替换 @tailwind directives
  • @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 文件体积也缩小了。

💬 Comments