Tailwind CSS4 安装(NPM)
核对 Node.js/npm 环境检查、Tailwind CSS v4 自动内容源检测及 @tailwindcss/cli、@tailwindcss/vite、@tailwindcss/postcss 三种集成流程与离线 Chromium 层叠实测。
学完这一章,你能够
- 核对 Node.js/npm 环境检查、Tailwind CSS v4 自动内容源检测及 @tailwindcss/cli、@tailwindcss/vite、@tailwindcss/postcss 三种集成流程与离线 Chromium 层叠实测。
Node.js 环境准备与镜像源配置
采用 NPM 方式安装 Tailwind CSS 4 前,应先运行 `node -v` 与 `npm -v` 确认本地已就绪 Node.js 及 npm(若尚未安装可先参考 Node.js 环境配置教程)。国内网络访问官方源较慢时,可将 npm 镜像切换至 `https://registry.npmmirror.com` 或全局安装 `cnpm` 后以 `cnpm install <包名>` 加速依赖下载(原淘宝源域名 `npm.taobao.org` 已全面迁移至 npmmirror)。
Tailwind CSS 4 核心变化与 CLI 独立构建流程
相比 v3 需要手工维护 `tailwind.config.js` 的 `content` 路径数组,Tailwind CSS 4 改为自动扫描项目中的 HTML、JS/TS 等模板文件并默认忽略 `.gitignore` 与 `node_modules`,同时转向 CSS 优先配置。从零搭建最快的方式是安装 `tailwindcss` 与 `@tailwindcss/cli`:第一步在入口 CSS(如 `src/input.css`)顶部写入 `@import "tailwindcss";`;第二步运行 `npx @tailwindcss/cli -i ./src/input.css -o ./src/output.css --watch` 持续扫描并编译输出;第三步在 `src/index.html` 的 `<head>` 中链接 `./output.css` 并编写 `text-3xl font-bold underline`。本站离线实验验证了 v4 风格自动扫描精准收录 `src/app.tsx`、`src/index.html` 而自动跳过 `dist/` 与 `node_modules/`,并在 Chromium 中核验 `@layer theme, base, components, utilities` 驱动 CSS 变量 `--text-3xl: 1.875rem` 将标题渲染为 `30px`、`36px` 行高、`700` 字重与下划线。
作为 Vite 插件无缝集成
Vite 借助浏览器原生 ES 模块提供极速热更新,将 Tailwind CSS 4 作为 Vite 插件接入是与 Laravel、SvelteKit、React Router、Nuxt、SolidJS 等现代框架集成最顺滑的路径。完整流程为五步:1)安装 `tailwindcss` 与 `@tailwindcss/vite`;2)在 `vite.config.ts` 的 `plugins` 数组中注册 `tailwindcss()`;3)在主样式文件加入 `@import "tailwindcss";`;4)执行 `npm run dev` 启动开发构建;5)确保 HTML `<head>` 已加载样式(多数框架会自动注入)即可直接使用工具类。本站离线 Chromium 实测验证了 `@layer base, components, utilities` 声明顺序下,即使 `@layer utilities` 写在样式表最前,`.text-brand`(`rgb(37, 99, 235)`)依然优先覆盖 `@layer components` 与 `@layer base` 的颜色规则。
作为 PostCSS 插件集成
在 Next.js、Angular 或既有 PostCSS 工具链项目中,可通过独立包 `@tailwindcss/postcss` 接入 Tailwind CSS 4:1)安装 `tailwindcss`、`@tailwindcss/postcss` 与 `postcss`;2)在 `postcss.config.mjs` 中导出 `plugins: { "@tailwindcss/postcss": {} }`;3)在样式入口写入 `@import "tailwindcss";`;4)运行 `npm run dev` 启动构建;5)在 HTML `<head>` 引入编译后的 `/dist/styles.css` 并应用 `text-3xl font-bold underline`。本站离线 Chromium 复测编译后样式表对该标题同样准确输出 `30px`、`700` 与 `underline`。
离线核验 Tailwind CSS v4 自动源扫描、CSS 变量主题令牌与 @layer 级联优先级
"""Offline Playwright Chromium lab for Tailwind CSS Ch 04 (tailwindcss4-installbynpm)."""
import json
import os
import re
import tempfile
from pathlib import Path
from playwright.sync_api import sync_playwright
V4_COMPILED_CSS = """
@layer theme, base, components, utilities;
@layer theme {
:root {
--font-sans: system-ui, -apple-system, sans-serif;
--text-3xl: 1.875rem;
--text-3xl--line-height: 2.25rem;
--font-weight-bold: 700;
--color-brand: #2563eb;
}
}
@layer base {
*, *::before, *::after { box-sizing: border-box; }
body { margin: 0; font-family: var(--font-sans); font-size: 16px; }
h1 { font-size: 1rem; font-weight: 400; margin: 0; }
}
@layer components {
.demo-title { color: #64748b; }
}
@layer utilities {
.text-3xl { font-size: var(--text-3xl); line-height: var(--text-3xl--line-height); }
.font-bold { font-weight: var(--font-weight-bold); }
.underline { text-decoration-line: underline; }
.text-brand { color: var(--color-brand); }
}
"""
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: Tailwind v4 CSS-first @layer theme/base/components/utilities & CSS custom properties
page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{V4_COMPILED_CSS}</style></head>
<body>
<h1 id="v4-h1" class="demo-title text-3xl font-bold underline text-brand">Hello world!</h1>
</body></html>""")
actual1 = page.eval_on_selector("#v4-h1", """el => {
const s = getComputedStyle(el);
const root = getComputedStyle(document.documentElement);
return {
tokenText3xl: root.getPropertyValue('--text-3xl').trim(),
fontSize: s.fontSize,
lineHeight: s.lineHeight,
fontWeight: s.fontWeight,
textDecorationLine: s.textDecorationLine,
color: s.color,
};
}""")
expected1 = {
"tokenText3xl": "1.875rem",
"fontSize": "30px",
"lineHeight": "36px",
"fontWeight": "700",
"textDecorationLine": "underline",
"color": "rgb(37, 99, 235)",
}
cases.append(dict(
name="v4_import_css_first_theme_tokens",
expected=expected1,
actual=actual1,
passed=(actual1 == expected1),
))
# Case 2: Tailwind v4 automatic content detection (skips gitignored / node_modules / binary)
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / ".gitignore").write_text("dist/\nnode_modules/\n", encoding="utf-8")
(root / "src").mkdir()
(root / "dist").mkdir()
(root / "node_modules/pkg").mkdir(parents=True)
(root / "src/index.html").write_text(
'<h1 class="text-3xl font-bold underline">Hello world!</h1>', encoding="utf-8"
)
(root / "src/app.tsx").write_text(
'export const C = () => <div className="p-4 text-brand">v4</div>;', encoding="utf-8"
)
(root / "dist/output.css").write_text(".ignored-from-dist { color: red; }", encoding="utf-8")
(root / "node_modules/pkg/index.js").write_text('const c = "ignored-dep";', encoding="utf-8")
ignored_dirs = {
line.strip().rstrip("/")
for line in (root / ".gitignore").read_text(encoding="utf-8").splitlines()
if line.strip() and not line.startswith("#")
}
scanned_files = []
tokens = set()
for path in sorted(root.rglob("*")):
if not path.is_file():
continue
rel = path.relative_to(root)
if any(part in ignored_dirs for part in rel.parts) or rel.name == ".gitignore":
continue
if path.suffix in {".html", ".js", ".ts", ".jsx", ".tsx", ".vue"}:
scanned_files.append(rel.as_posix())
txt = path.read_text(encoding="utf-8")
for m in re.findall(r'(?:class|className)="([^"]+)"', txt):
tokens.update(m.split())
actual2 = {
"scannedFiles": scanned_files,
"extractedClasses": sorted(tokens),
}
expected2 = {
"scannedFiles": ["src/app.tsx", "src/index.html"],
"extractedClasses": ["font-bold", "p-4", "text-3xl", "text-brand", "underline"],
}
cases.append(dict(
name="v4_auto_content_detection_scan",
expected=expected2,
actual=actual2,
passed=(actual2 == expected2),
))
# Case 3: Vite plugin integration layer ordering (@layer utilities beats @layer components/base)
page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8">
<style>
@layer base, components, utilities;
@layer utilities {{ .text-brand {{ color: #2563eb; }} }}
@layer components {{ .demo-title {{ color: #ef4444; }} }}
@layer base {{ h1 {{ color: #000000; }} }}
</style></head>
<body>
<h1 id="vite-h1" class="demo-title text-brand">Vite + Tailwind v4</h1>
</body></html>""")
actual3 = {
"resolvedColor": page.eval_on_selector("#vite-h1", "el => getComputedStyle(el).color"),
"configEntry": "vite.config.ts",
"pluginPackage": "@tailwindcss/vite",
"cssDirective": '@import "tailwindcss";',
}
expected3 = {
"resolvedColor": "rgb(37, 99, 235)",
"configEntry": "vite.config.ts",
"pluginPackage": "@tailwindcss/vite",
"cssDirective": '@import "tailwindcss";',
}
cases.append(dict(
name="v4_vite_plugin_layer_precedence",
expected=expected3,
actual=actual3,
passed=(actual3 == expected3),
))
# Case 4: PostCSS plugin integration output verification
page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{V4_COMPILED_CSS}</style></head>
<body>
<h1 id="postcss-h1" class="text-3xl font-bold underline">Hello world!</h1>
</body></html>""")
actual4 = {
"configEntry": "postcss.config.mjs",
"pluginKey": "@tailwindcss/postcss",
"fontSize": page.eval_on_selector("#postcss-h1", "el => getComputedStyle(el).fontSize"),
"fontWeight": page.eval_on_selector("#postcss-h1", "el => getComputedStyle(el).fontWeight"),
"textDecorationLine": page.eval_on_selector("#postcss-h1", "el => getComputedStyle(el).textDecorationLine"),
}
expected4 = {
"configEntry": "postcss.config.mjs",
"pluginKey": "@tailwindcss/postcss",
"fontSize": "30px",
"fontWeight": "700",
"textDecorationLine": "underline",
}
cases.append(dict(
name="v4_postcss_plugin_output_check",
expected=expected4,
actual=actual4,
passed=(actual4 == expected4),
))
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
run()
- 核对 --text-3xl 令牌渲染 30px/36px/700/underline、自动扫描跳过 dist/ 与 node_modules/ 提取 5 个类名,以及 @layer utilities 覆盖 components/base 的 Chromium 实测。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:baa81c924314b2898c4a6367e60fdafb2e319d3e714a64eea50cb246e5f19f3b
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:4bd727fea282ba59ce34cb5ec35a223839fda752b909eea46e87806a510ab867
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
Tailwind CSS 4 相比 v3 在入口 CSS 写法与内容源检测上有哪两项最显著的简化?
展开参考解答
入口 CSS 由三条 `@tailwind` 指令简化为单条 `@import "tailwindcss";`;内容源检测改为自动发现项目模板并跳过 `.gitignore` 与 `node_modules`,不再强制要求在 `tailwind.config.js` 手写 `content` 路径。