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

在离线 Chromium 中实测 Vite React 入口约定、加减计数器、HelloWorld 组件与 CSS Modules 绑定

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-vite.py
explore-vite.py266 行
"""Offline Playwright Chromium lab for React Ch 04 (vite)."""
from __future__ import annotations

import json
from playwright.sync_api import sync_playwright

MICRO_REACT_JS = r"""
var React = (() => {
  const Fragment = Symbol("Fragment");
  const StrictMode = Symbol("StrictMode");
  function createElement(type, props, ...children) {
    const flat = [];
    const push = (c) => {
      if (Array.isArray(c)) c.forEach(push);
      else if (c !== null && c !== undefined && c !== false && c !== true) flat.push(c);
    };
    children.forEach(push);
    return { type, props: Object.assign({}, props || {}, { children: flat }) };
  }
  let currentRoot = null;
  let hookIndex = 0;
  function useState(initial) {
    const root = currentRoot;
    const idx = hookIndex++;
    if (!(idx in root.hooks)) {
      root.hooks[idx] = typeof initial === "function" ? initial() : initial;
    }
    const setState = (next) => {
      const prev = root.hooks[idx];
      root.hooks[idx] = typeof next === "function" ? next(prev) : next;
      root.rerender();
    };
    return [root.hooks[idx], setState];
  }
  function resolveTree(node) {
    if (node === null || node === undefined || typeof node === "boolean") return null;
    if (typeof node === "string" || typeof node === "number") return { type: "#text", text: String(node) };
    if (node.type === Fragment || node.type === StrictMode) {
      return {
        type: "#fragment",
        children: (node.props.children || []).map(resolveTree).filter(Boolean),
      };
    }
    if (typeof node.type === "function") return resolveTree(node.type(node.props));
    const children = [];
    for (const c of node.props.children || []) {
      const r = resolveTree(c);
      if (!r) continue;
      if (r.type === "#fragment") children.push(...r.children);
      else children.push(r);
    }
    return { type: node.type, props: node.props, children };
  }
  function createDom(vnode) {
    if (vnode.type === "#text") return document.createTextNode(vnode.text);
    if (vnode.type === "#fragment") {
      const frag = document.createDocumentFragment();
      vnode.children.forEach((c) => frag.appendChild(createDom(c)));
      return frag;
    }
    const el = document.createElement(vnode.type);
    for (const [k, v] of Object.entries(vnode.props || {})) {
      if (k === "children" || k === "key") continue;
      if (k === "className") el.setAttribute("class", v);
      else if (k === "style" && typeof v === "object") Object.assign(el.style, v);
      else if (k.startsWith("on") && typeof v === "function") el.addEventListener(k.slice(2).toLowerCase(), v);
      else el.setAttribute(k, String(v));
    }
    vnode.children.forEach((c) => el.appendChild(createDom(c)));
    return el;
  }
  function createRoot(container) {
    return {
      container,
      hooks: {},
      lastElement: null,
      render(element) {
        this.lastElement = element;
        this.rerender();
      },
      rerender() {
        currentRoot = this;
        hookIndex = 0;
        const resolved = resolveTree(this.lastElement);
        this.container.innerHTML = "";
        if (resolved) this.container.appendChild(createDom(resolved));
        currentRoot = null;
      },
    };
  }
  return { createElement, Fragment, StrictMode, useState, createRoot };
})();
var ReactDOM = { createRoot: React.createRoot };
"""


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main() -> None:
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        try:
            page = browser.new_page()

            # Case 1: Vite project entry structure (root index.html + module main.jsx + StrictMode)
            page.set_content("""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>Vite + React</title></head>
<body>
<div id="root"></div>
<script type="module" data-entry="/src/main.jsx"></script>
</body></html>""")
            actual1 = page.evaluate("""() => {
              const s = document.querySelector("script[type='module']");
              const pkg = { scripts: { dev: "vite", build: "vite build" }, defaultPort: 5173, outDir: "dist/" };
              return {
                hasRoot: Boolean(document.getElementById("root")),
                moduleEntry: s ? s.getAttribute("data-entry") : null,
                devScript: pkg.scripts.dev,
                buildScript: pkg.scripts.build,
                defaultPort: pkg.defaultPort,
                outDir: pkg.outDir
              };
            }""")
            expected1 = {
                "hasRoot": True,
                "moduleEntry": "/src/main.jsx",
                "devScript": "vite",
                "buildScript": "vite build",
                "defaultPort": 5173,
                "outDir": "dist/",
            }
            cases.append({
                "name": "vite_scaffold_and_entry_check",
                "expected": expected1,
                "actual": actual1,
                "passed": actual1 == expected1,
            })

            # Case 2: Vite App.jsx useState counter (+1 and exercise -1 button) inside StrictMode
            page.set_content(f"""<!DOCTYPE html>
<html><body><div id="root"></div>
<script>{MICRO_REACT_JS}
function App() {{
  const [count, setCount] = React.useState(0);
  return React.createElement(
    "div", {{ className: "App" }},
    React.createElement("h1", null, "你好,React + Vite!"),
    React.createElement(
      "div", {{ className: "card" }},
      React.createElement("button", {{ id: "inc", onClick: () => setCount((c) => c + 1) }}, "当前计数:" + count),
      React.createElement("button", {{ id: "dec", onClick: () => setCount((c) => c - 1) }}, "减一")
    ),
    React.createElement("p", null, "编辑 ", React.createElement("code", null, "src/App.jsx"), " 并保存体验热更新!")
  );
}}
ReactDOM.createRoot(document.getElementById("root")).render(
  React.createElement(React.StrictMode, null, React.createElement(App, null))
);
</script></body></html>""")
            init_btn = page.text_content("#inc")
            page.click("#inc")
            page.click("#inc")
            after_inc = page.text_content("#inc")
            page.click("#dec")
            after_dec = page.text_content("#inc")
            actual2 = {
                "heading": page.text_content("h1"),
                "initial": init_btn,
                "afterTwoInc": after_inc,
                "afterOneDec": after_dec,
            }
            expected2 = {
                "heading": "你好,React + Vite!",
                "initial": "当前计数:0",
                "afterTwoInc": "当前计数:2",
                "afterOneDec": "当前计数:1",
            }
            cases.append({
                "name": "vite_app_counter_and_decrement",
                "expected": expected2,
                "actual": actual2,
                "passed": actual2 == expected2,
            })

            # Case 3: HelloWorld component with prop & fallback default
            page.set_content(f"""<!DOCTYPE html>
<html><body><div id="root"></div>
<script>{MICRO_REACT_JS}
function HelloWorld({{ name }}) {{
  return React.createElement("h2", null, "欢迎," + (name || "陌生人") + "!");
}}
function App() {{
  return React.createElement(
    "div", null,
    React.createElement(HelloWorld, {{ name: "蓝色天空" }}),
    React.createElement(HelloWorld, {{}})
  );
}}
ReactDOM.createRoot(document.getElementById("root")).render(React.createElement(App, null));
</script></body></html>""")
            actual3 = page.evaluate("""() => Array.from(document.querySelectorAll("#root h2")).map(n => n.textContent)""")
            expected3 = ["欢迎,蓝色天空!", "欢迎,陌生人!"]
            cases.append({
                "name": "vite_helloworld_component_props",
                "expected": expected3,
                "actual": actual3,
                "passed": actual3 == expected3,
            })

            # Case 4: CSS import, CSS Modules scoped class & SVG asset variable
            page.set_content(f"""<!DOCTYPE html>
<html><head><style>
.card_scoped_a1b2 {{ padding: 16px; border-radius: 8px; }}
</style></head><body><div id="root"></div>
<script>{MICRO_REACT_JS}
const styles = {{ card: "card_scoped_a1b2" }};
const viteLogo = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='32' height='32'></svg>";
function AssetDemo() {{
  return React.createElement(
    "div", {{ id: "box", className: styles.card }},
    React.createElement("img", {{ id: "logo", src: viteLogo, alt: "Vite logo" }})
  );
}}
ReactDOM.createRoot(document.getElementById("root")).render(React.createElement(AssetDemo, null));
</script></body></html>""")
            actual4 = page.evaluate("""() => {
              const box = document.getElementById("box");
              const cs = getComputedStyle(box);
              const img = document.getElementById("logo");
              return {
                className: box.className,
                padding: cs.padding,
                borderRadius: cs.borderRadius,
                logoAlt: img.getAttribute("alt"),
                isDataUri: img.getAttribute("src").startsWith("data:image/svg+xml")
              };
            }""")
            expected4 = {
                "className": "card_scoped_a1b2",
                "padding": "16px",
                "borderRadius": "8px",
                "logoAlt": "Vite logo",
                "isDataUri": True,
            }
            cases.append({
                "name": "vite_css_and_asset_binding",
                "expected": expected4,
                "actual": actual4,
                "passed": actual4 == expected4,
            })
        finally:
            browser.close()

    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/react-vite-lab/explore-vite.py

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

下载课程关联工程包:React

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

下载课程关联工程包:React

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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