蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线核验 Tailwind CSS 3 模板通配扫描、三层 @tailwind 优先级与 PostCSS 渲染

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-installbynpm.py
explore-installbynpm.py173 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/tailwindcss-installbynpm-lab/explore-installbynpm.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-installbynpm.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Tailwind CSS

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a649.zip

下载课程关联工程包:Tailwind CSS

课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a639.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习