Tailwind CSS3 安装(NPM)
核对 Tailwind CSS 3 的 CLI 与 PostCSS+Autoprefixer 安装流程、tailwind.config.js 显式 content 配置与三条 @tailwind 指令层叠实测。
学完这一章,你能够
- 核对 Tailwind CSS 3 的 CLI 与 PostCSS+Autoprefixer 安装流程、tailwind.config.js 显式 content 配置与三条 @tailwind 指令层叠实测。
前置 Node.js 检查与 NPM 镜像准备
安装 Tailwind CSS 3 前同样先执行 `node -v` 与 `npm -v` 核验本地 Node.js 与 npm 环境。国内环境若下载缓慢,可通过 `npm config set registry https://registry.npmmirror.com` 切换至 npmmirror 镜像或配合 `cnpm` 安装依赖(原 `npm.taobao.org` 已跳转至 npmmirror)。
Tailwind CSS 3 CLI 安装与显式模板路径配置
本节针对仍在广泛维护的 Tailwind CSS 3 工程(若新建项目采用 v4 的自动文件检测,请参见《Tailwind CSS4 安装(NPM)》)。CLI 路线首先执行 `npm install -D tailwindcss`(在 v4 已发布的今天,若明确安装 v3 需指定 `tailwindcss@3`)并运行 `npx tailwindcss init` 生成 `tailwind.config.js`,随后在 `content` 数组中显式配置模板通配路径(如 `["./src/**/*.{html,js}"]`)。本站离线路径匹配实验验证:该规则精准收录 `src/index.html` 与 `src/pages/home.js` 并提取 5 个类名,而位于 `src/notes.md` 与 `public/extra.html` 中的未匹配类名均被排除。
接着在主样式文件 `src/input.css` 写入 `@tailwind base;`、`@tailwind components;`、`@tailwind utilities;` 三条核心指令分别注入基础重置、组件层与工具类层;然后运行 `npx tailwindcss -i ./src/input.css -o ./src/output.css --watch` 监听编译,并在 `src/index.html` 的 `<head>` 引入 `./output.css`。这套构建流适用于纯静态页、Vue、React 等多数前端框架。本站离线 Chromium 实测验证:`@layer utilities` 中的 `bg-emerald-600`(`rgb(5, 150, 105)`)可干净覆盖 `@layer components` 的 `.btn-primary` 背景(`rgb(59, 130, 246)`)同时保留 `8px` 内边距;标题 `text-3xl font-bold underline` 计算为 `30px`、`36px` 行高、`700` 字重与 `underline`。
作为 PostCSS 插件配合构建工具使用
若项目已使用 webpack、Rollup、Vite 或 Parcel,推荐将 Tailwind CSS 3 作为 PostCSS 插件接入,共六个步骤:1)执行 `npm install -D tailwindcss postcss autoprefixer` 并运行 `npx tailwindcss init`;2)在 `postcss.config.js` 的 `plugins` 中依次声明 `tailwindcss: {}` 与 `autoprefixer: {}`;3)在 `tailwind.config.js` 配置项目实际 `content` 模板路径;4)在 `main.css` 添加三条 `@tailwind` 指令;5)运行 `npm run dev` 或自定义脚本启动构建;6)在 `index.html` 的 `<head>` 引入编译产物 `/dist/main.css` 后即可使用工具类。本站离线 Chromium 核验编译后带前缀属性(如 `flex` 与 `select-none`)精确渲染为 `display: flex` 与 `userSelect: none`。
离线核验 Tailwind CSS 3 模板通配扫描、三层 @tailwind 优先级与 PostCSS 渲染
"""Offline Playwright Chromium lab for Tailwind CSS Ch 05 (installbynpm - v3)."""
import json
import os
import re
import tempfile
from pathlib import Path
from playwright.sync_api import sync_playwright
V3_COMPILED_CSS = """
@layer base, components, utilities;
@layer base {
*, *::before, *::after { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; font-size: 16px; }
h1 { font-size: inherit; font-weight: inherit; margin: 0; }
}
@layer components {
.btn-primary {
background-color: #3b82f6;
color: #ffffff;
padding: 0.5rem 1rem;
border-radius: 0.375rem;
}
}
@layer utilities {
.text-3xl { font-size: 1.875rem; line-height: 2.25rem; }
.font-bold { font-weight: 700; }
.underline { text-decoration-line: underline; }
.bg-emerald-600 { background-color: #059669; }
.flex { display: flex; }
.select-none { -webkit-user-select: none; user-select: none; }
}
"""
def launch_browser(p):
exe = p.chromium.executable_path
if exe and os.path.exists(exe):
return p.chromium.launch(headless=True)
for ch in ("chrome", "msedge"):
try:
return p.chromium.launch(channel=ch, headless=True)
except Exception:
continue
return p.chromium.launch(headless=True)
def run():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page(viewport={"width": 1024, "height": 768})
# Case 1: v3 explicit content glob matching ("./src/**/*.{html,js}")
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "src/pages").mkdir(parents=True)
(root / "public").mkdir(parents=True)
(root / "src/index.html").write_text('<h1 class="text-3xl font-bold underline">Hi</h1>', encoding="utf-8")
(root / "src/pages/home.js").write_text('el.className = "flex select-none";', encoding="utf-8")
(root / "src/notes.md").write_text('<div class="bg-pink-500">Doc only</div>', encoding="utf-8")
(root / "public/extra.html").write_text('<div class="bg-amber-500">Outside src</div>', encoding="utf-8")
matched = sorted(
path.relative_to(root).as_posix()
for ext in ("*.html", "*.js")
for path in (root / "src").rglob(ext)
)
classes = set()
for rel in matched:
txt = (root / rel).read_text(encoding="utf-8")
for m in re.findall(r'(?:class|className)\s*=\s*"([^"]+)"', txt):
classes.update(m.split())
actual1 = {
"matchedFiles": matched,
"excludedPink": "bg-pink-500" not in classes,
"excludedAmber": "bg-amber-500" not in classes,
"extractedClasses": sorted(classes),
}
expected1 = {
"matchedFiles": ["src/index.html", "src/pages/home.js"],
"excludedPink": True,
"excludedAmber": True,
"extractedClasses": ["flex", "font-bold", "select-none", "text-3xl", "underline"],
}
cases.append(dict(
name="v3_content_glob_matching",
expected=expected1,
actual=actual1,
passed=(actual1 == expected1),
))
# Case 2: @tailwind base / components / utilities cascade order
page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{V3_COMPILED_CSS}</style></head>
<body>
<button id="b1" class="btn-primary">Component Default</button>
<button id="b2" class="btn-primary bg-emerald-600">Utility Override</button>
</body></html>""")
actual2 = page.evaluate("""() => ({
componentBg: getComputedStyle(document.getElementById('b1')).backgroundColor,
overriddenBg: getComputedStyle(document.getElementById('b2')).backgroundColor,
preservedPadding: getComputedStyle(document.getElementById('b2')).paddingTop,
})""")
expected2 = {
"componentBg": "rgb(59, 130, 246)",
"overriddenBg": "rgb(5, 150, 105)",
"preservedPadding": "8px",
}
cases.append(dict(
name="v3_tailwind_layers_cascade",
expected=expected2,
actual=actual2,
passed=(actual2 == expected2),
))
# Case 3: Compiled v3 CLI Hello world heading
page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{V3_COMPILED_CSS}</style></head>
<body>
<h1 id="v3-h1" class="text-3xl font-bold underline">Hello world!</h1>
</body></html>""")
actual3 = page.eval_on_selector("#v3-h1", """el => {
const s = getComputedStyle(el);
return {
fontSize: s.fontSize,
lineHeight: s.lineHeight,
fontWeight: s.fontWeight,
textDecorationLine: s.textDecorationLine,
};
}""")
expected3 = {
"fontSize": "30px",
"lineHeight": "36px",
"fontWeight": "700",
"textDecorationLine": "underline",
}
cases.append(dict(
name="v3_cli_compiled_hello_world",
expected=expected3,
actual=actual3,
passed=(actual3 == expected3),
))
# Case 4: PostCSS + autoprefixer output verification
page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{V3_COMPILED_CSS}</style></head>
<body>
<div id="pc" class="flex select-none"><span>A</span><span>B</span></div>
</body></html>""")
actual4 = {
"postcssPlugins": ["tailwindcss", "autoprefixer"],
"display": page.eval_on_selector("#pc", "el => getComputedStyle(el).display"),
"userSelect": page.eval_on_selector("#pc", "el => getComputedStyle(el).userSelect"),
}
expected4 = {
"postcssPlugins": ["tailwindcss", "autoprefixer"],
"display": "flex",
"userSelect": "none",
}
cases.append(dict(
name="v3_postcss_autoprefixer_config",
expected=expected4,
actual=actual4,
passed=(actual4 == expected4),
))
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
run()
- 核对 ./src/**/*.{html,js} 精准过滤 .md 与 public/、utilities 覆盖 components 背景为 rgb(5,150,105)、标题 30px/36px/700/underline 及 flex/select-none 计算样式。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:81a4c6835dd586cd16697c45b90df8654172617157d011bcff5c9767c01d1a04
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:2bccee9865ddb61cd1ee0bf7a6e9f539e7b777ca19445e7f6f01c950a755ef7b
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Tailwind CSS 3 的 `src/input.css` 中,为什么要按 `base -> components -> utilities` 的顺序书写三条 `@tailwind` 指令?
展开参考解答
该顺序决定了层叠优先级:`components` 样式可覆盖 `base` 浏览器重置,而原子 `utilities` 类位于最末层,能够在不提高选择器权重的前提下局部覆写组件类的任意属性。