症状: 首次访问时偶发样式丢失,刷新后恢复正常
原因: 使用 CDN 版本的 Tailwind CSS (https://cdn.tailwindcss.com)
将 Tailwind CSS 从 CDN 迁移到本地构建,样式打包到 bundle 中。
2026-01-31
tailwind.config.jsexport default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
"./*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
"./pages/**/*.{js,ts,jsx,tsx}",
"./hooks/**/*.{js,ts,jsx,tsx}",
"./contexts/**/*.{js,ts,jsx,tsx}",
"./utils/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {
fontFamily: {
sans: ['Inter', ...],
},
animation: {
'wave-h': 'wave-h 2s ease-in-out infinite',
'wave-v': 'wave-v 2s ease-in-out infinite',
},
},
},
plugins: [],
}
作用:
postcss.config.jsexport default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
作用:
index.css@tailwind base;
@tailwind components;
@tailwind utilities;
/* 全局样式和自定义动画 */
作用:
index.tsximport './index.css'; // 新增
作用:
index.html<!-- 删除 -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- 删除内联样式 -->
<style>...</style>
作用:
| 特性 | CDN 方式 | 本地构建 |
|---|---|---|
| 首次加载速度 | ❌ 慢(需下载 CDN) | ✅ 快(已打包) |
| 样式稳定性 | ❌ 依赖网络 | ✅ 本地保证 |
| 自定义配置 | ❌ 不支持 | ✅ 完全支持 |
| 生产体积 | ❌ 大(完整库) | ✅ 小(Tree-shaking) |
| 离线可用 | ❌ 不可用 | ✅ 可用 |
| 构建时间 | ✅ 无需构建 | ⚠️ 略增加 |
# 停止当前服务器(Ctrl+C)
# 重新启动
npm run dev
npm run build
检查 dist 目录中是否有 CSS 文件被打包。
✅ 首次访问样式立即加载
✅ 无样式闪烁(FOUC)
✅ 离线可用
✅ 更小的生产体积
开发服务器需要重启
样式变化需要刷新
内容路径要正确
tailwind.config.js 中的 content 路径必须包含所有使用 Tailwind 的文件自定义样式位置
index.css解决:
# 1. 检查是否导入了 index.css
# 2. 重启开发服务器
npm run dev
# 3. 清除 node_modules/.vite 缓存
rm -rf node_modules/.vite
npm run dev
解决:
tailwind.config.js 的 content 路径解决:
npm run builddist 目录是否有 CSS 文件index.html 正确引用了 CSS