Tailwind 样式失效主因是 PostCSS 配置缺失或错误:postcss.config.js 必须存在且用 export default(ESM)或 .cjs 后缀;content 字段需覆盖所有 JSX/TSX 路径;@tailwind 指令须裸露在 index.css 顶层并被正确引入。

直接装好就能用,但 postcss 配置错一步,@tailwind 指令就不生效,页面完全没样式——这不是 Tailwind 本身的问题,而是 PostCSS 插件链没接上。
postcss.config.js 文件必须存在且导出正确插件对象
很多项目卡在这一步:只装了 tailwindcss 和 autoprefixer,却没让 PostCSS 知道要调用它们。Vite 或 CRA 默认不读 postcss.config.js,除非它真实存在且格式合法。
- 如果你的项目是
type: "module"(package.json 里有),必须用export default语法,不能用module.exports - 常见错误写法:
module.exports = { plugins: { tailwindcss: {} } }→ 在 ESM 环境下会报ReferenceError: module is not defined - 正确写法(ESM):
export default { plugins: { tailwindcss: {}, autoprefixer: {}, } } - 或者改后缀为
postcss.config.cjs,继续用module.exports
tailwind.config.js 的 content 字段必须覆盖所有 JSX/TSX 路径
这个字段不是“可选配置”,而是生产构建时 CSS Tree Shaking 的唯一依据。漏掉路径,对应组件里的 class 就会被当成未使用而删掉,开发时看着正常,build 后样式消失。
- 必须包含
"./src/**/*.{js,jsx,ts,tsx}",如果用了public/index.html里也写 class,得加上"./public/index.html" - 若用 Vite + React + TSX,推荐写成
"./src/**/*.{js,jsx,ts,tsx}",不用额外加.d.ts或测试文件 - 注意路径是 glob 模式,不是正则;
**表示递归任意层级,*只匹配当前层
@tailwind 指令必须在 index.css 顶层且无条件引入
@tailwind base、@tailwind components、@tailwind utilities 这三行不是“建议添加”,而是 Tailwind 的样式注入入口。顺序不能换,也不能包裹在 @layer 或媒体查询里。
- 错误示例:
@layer base { @tailwind base; }→@tailwind必须在最外层 - 错误示例:把这三行写在
src/App.css里 → CRA/Vite 只处理index.css入口,其他 CSS 不触发 Tailwind 解析 - 确保
src/index.js或src/main.jsx中 import 了./index.css,否则整个链路断开
最容易被忽略的是:Tailwind 的 JIT 编译器只在开发服务器运行时监听文件变化,但它的解析完全依赖 content 字段和 PostCSS 插件是否就位。少一个环节,就只是纯 CSS 文件,没有类生成。别猜“是不是版本问题”,先检查 postcss.config.js 是否真的被读取、content 是否真扫到了你的组件文件、@tailwind 是否裸露在 index.css 顶层。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











