"""Offline Playwright Chromium lab for React Ch 41: Production Build Artifacts, Gitignore & Vercel SPA Rewrite."""
import hashlib
import json
import tempfile
import threading
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from playwright.sync_api import sync_playwright
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
DEV_JS = """
// Unused helper that tree-shaking removes in production build
export function unusedDebugHelper() {
const verbose = "this debug block is stripped by tree-shaking";
return verbose.repeat(8);
}
async function bootApp() {
const res = await fetch('/posts.json');
const posts = await res.json();
const m = window.location.pathname.match(/^\\/post\\/(\\d+)$/);
const root = document.getElementById('root');
if (m) {
const found = posts.find(p => p.id === Number(m[1]));
root.innerHTML = found
? `<article class="post-view"><h1>${found.title}</h1><p>${found.category}</p></article>`
: `<div class="not-found">Not Found</div>`;
} else {
root.innerHTML = `<div class="home"><h1>Blog Home</h1><p class="count">${posts.length}</p></div>`;
}
}
bootApp();
""".strip()
PROD_JS = (
"async function b(){const r=await fetch('/posts.json'),p=await r.json(),"
"m=location.pathname.match(/^\\/post\\/(\\d+)$/),e=document.getElementById('root');"
"if(m){const f=p.find(x=>x.id===Number(m[1]));e.innerHTML=f?`<article class=\"post-view\"><h1>${f.title}</h1><p>${f.category}</p></article>`:'<div class=\"not-found\">Not Found</div>'}"
"else{e.innerHTML=`<div class=\"home\"><h1>Blog Home</h1><p class=\"count\">${p.length}</p></div>`}}b();"
)
PROD_CSS = "body{margin:0;background:#f5f5f5;color:#222}.post-view{max-width:720px;margin:0 auto}"
POSTS_DATA = [
{"id": 1, "title": "React 入门完全指南", "category": "React"},
{"id": 2, "title": "JavaScript 异步编程详解", "category": "JavaScript"},
{"id": 3, "title": "CSS Grid 布局实战", "category": "CSS"},
]
FAVICON_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><circle cx="8" cy="8" r="6" fill="#61dafb"/></svg>'
def short_hash(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:8]
def build_dist(dist_dir: Path):
js_hash = short_hash(PROD_JS)
css_hash = short_hash(PROD_CSS)
assets_dir = dist_dir / "assets"
assets_dir.mkdir(parents=True, exist_ok=True)
js_name = f"index-{js_hash}.js"
css_name = f"index-{css_hash}.css"
(assets_dir / js_name).write_text(PROD_JS, encoding="utf-8")
(assets_dir / css_name).write_text(PROD_CSS, encoding="utf-8")
(dist_dir / "posts.json").write_text(json.dumps(POSTS_DATA, ensure_ascii=False), encoding="utf-8")
(dist_dir / "favicon.svg").write_text(FAVICON_SVG, encoding="utf-8")
index_html = (
f'<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8">'
f'<title>React Blog Prod Preview</title>'
f'<link rel="icon" href="/favicon.svg">'
f'<link rel="stylesheet" href="/assets/{css_name}">'
f'</head><body><div id="root"></div>'
f'<script type="module" src="/assets/{js_name}"></script></body></html>'
)
(dist_dir / "index.html").write_text(index_html, encoding="utf-8")
return js_name, css_name, js_hash, css_hash
def main():
cases = []
with tempfile.TemporaryDirectory() as tmp:
dist_dir = Path(tmp) / "dist"
js_name, css_name, js_hash, css_hash = build_dist(dist_dir)
mutated_hash = short_hash(PROD_JS + "/*v2*/")
# Case 1: Content hash cache busting, minification/tree-shaking & public/ copy
c1_actual = {
"js_filename": js_name,
"css_filename": css_name,
"hash_changes_on_edit": js_hash != mutated_hash,
"unused_stripped": "unusedDebugHelper" not in PROD_JS,
"minified_smaller": len(PROD_JS) < len(DEV_JS),
"public_copied_files": sorted(p.name for p in dist_dir.iterdir() if p.is_file()),
}
c1_expected = {
"js_filename": f"index-{js_hash}.js",
"css_filename": f"index-{css_hash}.css",
"hash_changes_on_edit": True,
"unused_stripped": True,
"minified_smaller": True,
"public_copied_files": ["favicon.svg", "index.html", "posts.json"],
}
cases.append({
"name": "dist_content_hash_and_tree_shaking",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
})
# Case 2: .gitignore & Vercel preset + SPA vercel.json configuration verification
gitignore_rules = {"node_modules", "dist", ".env.local"}
candidate_paths = ["node_modules/react/index.js", "dist/index.html", "src/App.jsx", "package.json", "public/posts.json"]
ignored = [p for p in candidate_paths if p.split("/")[0] in gitignore_rules]
tracked = [p for p in candidate_paths if p.split("/")[0] not in gitignore_rules]
vercel_config = {
"framework": "vite",
"buildCommand": "npm run build",
"outputDirectory": "dist",
"rewrites": [{"source": "/(.*)", "destination": "/index.html"}],
}
c2_actual = {
"ignored_paths": ignored,
"tracked_paths": tracked,
"preset_framework": vercel_config["framework"],
"build_command": vercel_config["buildCommand"],
"output_dir": vercel_config["outputDirectory"],
"spa_rewrite_dest": vercel_config["rewrites"][0]["destination"],
}
c2_expected = {
"ignored_paths": ["node_modules/react/index.js", "dist/index.html"],
"tracked_paths": ["src/App.jsx", "package.json", "public/posts.json"],
"preset_framework": "vite",
"build_command": "npm run build",
"output_dir": "dist",
"spa_rewrite_dest": "/index.html",
}
cases.append({
"name": "gitignore_and_vercel_preset_check",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
})
# Local preview server supporting toggleable vercel.json SPA rewrite
rewrite_enabled = {"value": False}
class DistHandler(BaseHTTPRequestHandler):
def serve_file(self, file_path: Path, cache_control: str):
ext_types = {
".html": "text/html; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8",
".svg": "image/svg+xml",
}
data = file_path.read_bytes()
self.send_response(200)
self.send_header("Content-Type", ext_types.get(file_path.suffix, "application/octet-stream"))
self.send_header("Cache-Control", cache_control)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_GET(self):
rel = self.path.lstrip("/") or "index.html"
candidate = dist_dir / rel
if candidate.is_file():
cc = "public, max-age=31536000, immutable" if rel.startswith("assets/") else "no-cache"
self.serve_file(candidate, cc)
elif rewrite_enabled["value"]:
self.serve_file(dist_dir / "index.html", "no-cache")
else:
msg = b"404 Not Found"
self.send_response(404)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Content-Length", str(len(msg)))
self.end_headers()
self.wfile.write(msg)
def log_message(self, format, *args):
return
server = ThreadingHTTPServer(("127.0.0.1", 0), DistHandler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
base = f"http://127.0.0.1:{port}"
# Verify deep link /post/2 returns 404 before vercel.json rewrite
try:
urllib.request.urlopen(base + "/post/2")
status_without_rewrite = 200
except urllib.error.HTTPError as exc:
status_without_rewrite = exc.code
# Enable vercel.json SPA rewrite and load /post/2 in headless Chromium
rewrite_enabled["value"] = True
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
resp = page.goto(base + "/post/2")
status_with_rewrite = resp.status
page.locator(".post-view h1").wait_for(state="visible", timeout=5000)
deep_title = page.locator(".post-view h1").inner_text()
deep_cat = page.locator(".post-view p").inner_text()
post_max_w = page.locator(".post-view").evaluate("el => getComputedStyle(el).maxWidth")
c3_actual = {
"status_without_rewrite": status_without_rewrite,
"status_with_rewrite": status_with_rewrite,
"deep_title": deep_title,
"deep_cat": deep_cat,
"css_applied_max_width": post_max_w,
}
c3_expected = {
"status_without_rewrite": 404,
"status_with_rewrite": 200,
"deep_title": "JavaScript 异步编程详解",
"deep_cat": "JavaScript",
"css_applied_max_width": "720px",
}
cases.append({
"name": "spa_rewrite_deep_link_chromium",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
})
# Case 4: Preview cache headers & static public assets check
asset_resp = page.request.get(f"{base}/assets/{js_name}")
html_resp = page.request.get(f"{base}/")
posts_resp = page.request.get(f"{base}/posts.json")
c4_actual = {
"asset_status": asset_resp.status,
"asset_cache_control": asset_resp.headers.get("cache-control"),
"html_cache_control": html_resp.headers.get("cache-control"),
"posts_status": posts_resp.status,
"posts_count": len(posts_resp.json()),
}
c4_expected = {
"asset_status": 200,
"asset_cache_control": "public, max-age=31536000, immutable",
"html_cache_control": "no-cache",
"posts_status": 200,
"posts_count": 3,
}
cases.append({
"name": "preview_cache_headers_and_static_assets",
"expected": c4_expected,
"actual": c4_actual,
"passed": c4_actual == c4_expected,
})
browser.close()
finally:
server.shutdown()
server.server_close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/react-blog-deploy-vercel-lab/explore-blog-deploy-vercel.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-blog-deploy-vercel.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3155.zip