"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/tailwindcss-tailwindcss4-installbynpm-lab/explore-tailwindcss4-installbynpm.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tailwindcss4-installbynpm.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a639.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a659.zip