Tailwind CSS 安装(NPM)
·
Tailwind CSS v3 安装 (NPM) 学习笔记
一、安装步骤
1. 初始化项目
mkdir my-project && cd my-project
npm init -y
2. 安装 Tailwind CSS
npm install -D tailwindcss
3. 生成配置文件
npx tailwindcss init
生成 tailwind.config.js:
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [], // ← 需要配置模板路径
theme: {
extend: {},
},
plugins: [],
}
4. 配置内容路径
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
'./src/**/*.{html,js,jsx,ts,tsx,vue}',
// './public/**/*.html', // 如果 HTML 在 public 目录
],
theme: {
extend: {},
},
plugins: [],
}
content是必须配置的,Tailwind 据此扫描文件,只生成用到的工具类(Tree-shaking)。
5. 创建 CSS 入口文件
/* src/input.css */
@tailwind base; /* Preflight 重置样式 */
@tailwind components; /* 组件层 */
@tailwind utilities; /* 工具类层 */
6. 创建 HTML 文件
<!-- src/index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tailwind CSS v3</title>
<link rel="stylesheet" href="../dist/output.css">
</head>
<body class="bg-gray-50 text-gray-900 min-h-screen">
<div class="max-w-4xl mx-auto py-12 px-4">
<h1 class="text-4xl font-bold text-blue-600 mb-4">Hello Tailwind!</h1>
<p class="text-lg text-gray-600">使用 NPM 方式安装的 Tailwind CSS v3。</p>
</div>
</body>
</html>
7. 构建并监听
# 开发模式(监听文件变化,自动重新构建)
npx tailwindcss -i src/input.css -o dist/output.css --watch
# 生产构建(压缩输出)
npx tailwindcss -i src/input.css -o dist/output.css --minify
8. 配置 npm scripts
{
"scripts": {
"dev": "tailwindcss -i src/input.css -o dist/output.css --watch",
"build": "tailwindcss -i src/input.css -o dist/output.css --minify"
}
}
npm run dev # 开发
npm run build # 生产构建
二、项目结构
my-project/
├── package.json
├── tailwind.config.js ← Tailwind 配置
├── src/
│ ├── input.css ← CSS 入口
│ └── index.html ← 页面模板
└── dist/
└── output.css ← 构建产物(自动生成)
三、tailwind.config.js 完整配置
1. content — 模板路径
content: [
// 相对路径,支持 glob 模式
'./src/**/*.{html,js,jsx,ts,tsx,vue}',
'./public/**/*.html',
// 第三方组件库路径(确保其类名不被 Tree-shaking)
'./node_modules/my-ui-lib/**/*.js',
],
2. theme — 主题定制
theme: {
// 完全替换默认值(不推荐)
colors: { ... },
// 在默认值基础上扩展(推荐)
extend: {
colors: {
brand: {
50: '#eff6ff',
100: '#dbeafe',
200: '#bfdbfe',
300: '#93c5fd',
400: '#60a5fa',
500: '#3b82f6',
600: '#2563eb',
700: '#1d4ed8',
800: '#1e40af',
900: '#1e3a8a',
},
},
fontFamily: {
sans: ['"Microsoft YaHei"', 'system-ui', 'sans-serif'],
mono: ['"Fira Code"', 'monospace'],
},
spacing: {
'128': '32rem',
'144': '36rem',
},
borderRadius: {
'4xl': '2rem',
},
screens: {
'xs': '475px',
'3xl': '1920px',
},
animation: {
'fade-in': 'fadeIn 0.5s ease-out',
'slide-up': 'slideUp 0.3s ease-out',
},
keyframes: {
fadeIn: {
'0%': { opacity: '0', transform: 'translateY(10px)' },
'100%': { opacity: '1', transform: 'translateY(0)' },
},
slideUp: {
'0%': { opacity: '0', transform: 'translateY(20px)' },
'100%': { opacity: '1', transform: 'translateY(0)' },
},
},
boxShadow: {
'soft': '0 2px 15px -3px rgba(0, 0, 0, 0.07), 0 10px 20px -2px rgba(0, 0, 0, 0.04)',
},
},
},
3. plugins — 插件
plugins: [
require('@tailwindcss/forms'), // 表单样式重置
require('@tailwindcss/typography'), // 排版插件 (prose)
require('@tailwindcss/aspect-ratio'),// 宽高比
require('@tailwindcss/line-clamp'), // 文本截断 (v3.3+ 已内置)
],
安装插件:
npm install -D @tailwindcss/forms @tailwindcss/typography @tailwindcss/aspect-ratio
4. darkMode — 暗色模式
darkMode: 'class', // 通过 .dark 类手动切换
// darkMode: 'media', // 跟随系统偏好(默认)
5. 完整配置示例
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
'./src/**/*.{html,js,jsx,ts,tsx,vue}',
'./public/**/*.html',
],
darkMode: 'class',
theme: {
extend: {
colors: {
brand: {
50: '#eff6ff',
500: '#3b82f6',
600: '#2563eb',
700: '#1d4ed8',
900: '#1e3a8a',
},
},
fontFamily: {
sans: ['"Microsoft YaHei"', 'system-ui', 'sans-serif'],
},
animation: {
'fade-in': 'fadeIn 0.5s ease-out',
},
keyframes: {
fadeIn: {
'0%': { opacity: '0' },
'100%': { opacity: '1' },
},
},
},
},
plugins: [
require('@tailwindcss/forms'),
require('@tailwindcss/typography'),
],
}
四、CSS 层与自定义样式
1. 三个层的作用
/* src/input.css */
/* base 层:Preflight 重置 + 全局样式 */
@tailwind base;
/* components 层:可复用组件类 */
@tailwind components;
/* utilities 层:工具类(优先级最高) */
@tailwind utilities;
优先级:utilities > components > base
2. 添加自定义样式
/* src/input.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
/* ===== base 层:全局重置 ===== */
@layer base {
body {
@apply bg-gray-50 text-gray-900;
}
h1, h2, h3 {
@apply font-bold tracking-tight;
}
a {
@apply text-blue-600 hover:text-blue-800 transition;
}
}
/* ===== components 层:组件类 ===== */
@layer components {
.btn {
@apply font-semibold py-2.5 px-5 rounded-lg transition duration-200
inline-flex items-center gap-2 cursor-pointer;
}
.btn-primary {
@apply bg-blue-500 hover:bg-blue-700 text-white;
}
.btn-danger {
@apply bg-red-500 hover:bg-red-700 text-white;
}
.btn-success {
@apply bg-green-500 hover:bg-green-700 text-white;
}
.btn-outline {
@apply border-2 border-blue-500 text-blue-500 hover:bg-blue-50;
}
.btn-sm {
@apply text-sm py-1.5 px-3;
}
.btn-lg {
@apply text-lg py-3 px-6;
}
.card {
@apply bg-white rounded-xl shadow-sm border border-gray-200 p-6;
}
.input-field {
@apply w-full px-3 py-2.5 border border-gray-300 rounded-lg
focus:border-blue-500 focus:ring-2 focus:ring-blue-200
outline-none transition;
}
.badge {
@apply text-xs font-semibold px-2.5 py-0.5 rounded-full;
}
}
/* ===== utilities 层:自定义工具类 ===== */
@layer utilities {
.text-balance {
text-wrap: balance;
}
.scrollbar-hide {
-ms-overflow-style: none;
scrollbar-width: none;
}
.scrollbar-hide::-webkit-scrollbar {
display: none;
}
}
3. 不使用 @layer 的样式
/* 不放在 @layer 中的样式优先级最高,可覆盖所有 Tailwind 类 */
.special-override {
color: red !important;
}
谨慎使用,通常应优先通过
@layer管理优先级。
五、与构建工具集成
1. Vite 集成(推荐)
npm create vite@latest my-project -- --template vanilla
cd my-project
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p # 生成 tailwind.config.js + postcss.config.js
// postcss.config.js
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
Vite 会自动处理 PostCSS,无需手动指定输出路径。
2. Webpack 集成
npm install -D tailwindcss postcss postcss-loader autoprefixer
npx tailwindcss init -p
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader', 'postcss-loader'],
},
],
},
};
3. Next.js 集成
npx create-next-app@latest my-project
cd my-project
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
// tailwind.config.js
content: [
'./app/**/*.{js,ts,jsx,tsx,mdx}',
'./pages/**/*.{js,ts,jsx,tsx,mdx}',
'./components/**/*.{js,ts,jsx,tsx,mdx}',
],
4. Vue CLI 集成
vue create my-project
cd my-project
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
// tailwind.config.js
content: [
'./public/index.html',
'./src/**/*.{vue,js,ts,jsx,tsx}',
],
六、PostCSS 与 Autoprefixer
1. 为什么需要 Autoprefixer
Tailwind v3 本身不添加浏览器前缀,需要 Autoprefixer 自动补全:
/* 输入 */
.example { appearance: none; }
/* Autoprefixer 输出 */
.example {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
2. 安装
npm install -D autoprefixer
3. 配置
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
4. 浏览器目标
// package.json
{
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
七、生产优化
1. Tree-shaking 原理
Tailwind v3 通过 content 配置扫描模板文件,只生成实际使用的工具类:
所有工具类 (约 100,000+) → 扫描模板 → 实际使用的类 (约 1,000)
2. 产出体积对比
| 方式 | 体积 (gzip) |
|---|---|
| CDN (全量) | ~300KB |
| NPM 开发构建 | ~50-100KB |
| NPM 生产构建 + minify | 5-15KB |
3. 构建命令
# 生产构建(压缩 + Tree-shaking)
NODE_ENV=production npx tailwindcss -i src/input.css -o dist/output.css --minify
4. 检查产出
# 查看生成的 CSS 大小
npx tailwindcss -i src/input.css -o dist/output.css --minify
ls -lh dist/output.css
八、常见问题
1. 样式不生效
原因:content 路径配置错误,类名被 Tree-shaking 移除。
// 检查 content 是否覆盖了你的模板文件
content: [
'./src/**/*.{html,js,jsx,ts,tsx,vue}', // 确保路径正确
],
2. 动态类名不生效
Tailwind 不识别拼接的类名:
<!-- 不生效:Tailwind 无法静态分析 -->
<div class="text-{{ color }}-500">错误</div>
解决方案:完整写出类名,确保被扫描到:
<!-- 正确 -->
<div class="{{ color === 'red' ? 'text-red-500' : 'text-blue-500' }}">正确</div>
或在 safelist 中强制保留:
// tailwind.config.js
module.exports = {
safelist: [
'text-red-500',
'text-blue-500',
'bg-red-500',
'bg-blue-500',
],
}
3. @apply 报错
确保 @apply 写在 @layer 块内,或使用独立 CSS 规则:
/* 正确 */
@layer components {
.btn { @apply bg-blue-500 text-white; }
}
/* 也正确(不在 @layer 中,优先级更高) */
.btn { @apply bg-blue-500 text-white; }
4. 修改配置后样式未更新
开发模式下 --watch 会自动重建。若未生效:
# 删除缓存重新构建
rm -rf node_modules/.cache
npx tailwindcss -i src/input.css -o dist/output.css --watch
5. 与现有 CSS 冲突
Tailwind 的 Preflight 会重置默认样式,可能导致第三方库样式异常:
/* 禁用 Preflight */
/* @tailwind base; */ ← 注释掉即可
@tailwind components;
@tailwind utilities;
或选择性引入:
@tailwind base;
/* 在 base 之后覆盖冲突样式 */
@layer base {
button { background: transparent; }
}
九、CDN vs NPM 对比总结
| 对比项 | CDN | NPM |
|---|---|---|
| 安装难度 | 极低 | 中 |
| 产出体积 | 大 (~300KB) | 小 (5-15KB gzip) |
| 自定义配置 | 有限 | 完整 |
| @apply / @layer | 有限支持 | 完整支持 |
| Tree-shaking | 不支持 | 支持 |
| 插件生态 | 部分支持 | 完整支持 |
| 构建工具集成 | 不支持 | 支持 |
| 浏览器兼容 | 依赖 JS | 纯 CSS |
| 适用场景 | 学习/原型 | 生产环境 |
总结:学习阶段可用 CDN 快速体验,正式项目务必使用 NPM 方式以获得完整功能和最优性能。
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐



所有评论(0)