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

离线 Chromium 本地预览服务实测 Vite 哈希产物、.gitignore 过滤与 vercel.json SPA 重写

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-blog-deploy-vercel.py
explore-blog-deploy-vercel.py253 行
"""Offline Playwright Chromium lab for Vue 3 Ch 48: Vite dist hash build, .gitignore & Vercel SPA rewrite preview."""
import hashlib
import json
import re
import tempfile
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
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")


def build_dist(dist_dir: Path, js_body: str, css_body: str, posts_bytes: bytes):
    assets_dir = dist_dir / "assets"
    assets_dir.mkdir(parents=True, exist_ok=True)
    js_hash = hashlib.sha256(js_body.encode("utf-8")).hexdigest()[:8]
    css_hash = hashlib.sha256(css_body.encode("utf-8")).hexdigest()[:8]
    js_name = f"index-{js_hash}.js"
    css_name = f"index-{css_hash}.css"
    (assets_dir / js_name).write_text(js_body, encoding="utf-8")
    (assets_dir / css_name).write_text(css_body, encoding="utf-8")
    (dist_dir / "posts.json").write_bytes(posts_bytes)
    html = (
        "<!DOCTYPE html><html lang='zh-CN'><head><meta charset='utf-8'>"
        f"<title>Blog Dist</title><link rel='stylesheet' href='/assets/{css_name}'></head>"
        f"<body><div id='app'></div><script src='/assets/{js_name}'></script></body></html>"
    )
    (dist_dir / "index.html").write_text(html, encoding="utf-8")
    return js_name, css_name


def start_preview_server(dist_dir: Path, vercel_cfg: dict):
    rewrites = vercel_cfg.get("rewrites", [])

    class DistHandler(BaseHTTPRequestHandler):
        def do_GET(self):
            req_path = self.path.split("?", 1)[0]
            rel = req_path.lstrip("/") or "index.html"
            target = (dist_dir / rel).resolve()
            if not str(target).startswith(str(dist_dir.resolve())) or not target.is_file():
                # Apply vercel.json SPA fallback rewrite if configured
                rewritten = None
                for rule in rewrites:
                    if re.fullmatch(rule["source"], req_path):
                        rewritten = dist_dir / rule["destination"].lstrip("/")
                        break
                if rewritten and rewritten.is_file():
                    target = rewritten
                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)
                    return
            data = target.read_bytes()
            ctype = "application/octet-stream"
            if target.suffix == ".html":
                ctype = "text/html; charset=utf-8"
            elif target.suffix == ".js":
                ctype = "application/javascript; charset=utf-8"
            elif target.suffix == ".css":
                ctype = "text/css; charset=utf-8"
            elif target.suffix == ".json":
                ctype = "application/json; charset=utf-8"
            self.send_response(200)
            self.send_header("Content-Type", ctype)
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            self.wfile.write(data)

        def log_message(self, format, *args):
            pass

    srv = HTTPServer(("127.0.0.1", 0), DistHandler)
    th = threading.Thread(target=srv.serve_forever, daemon=True)
    th.start()
    return srv, srv.server_address[1]


def main():
    posts_bytes = json.dumps(
        [
            {"id": 1, "title": "Vue3 入门完全指南"},
            {"id": 2, "title": "JS 异步编程详解"},
        ],
        ensure_ascii=False,
    ).encode("utf-8")

    js_v1 = (
        "(async()=>{const r=await fetch('/posts.json');const ps=await r.json();"
        "const m=location.pathname.match(/^\\/post\\/(\\d+)$/);"
        "const el=document.getElementById('app');"
        "if(m){const p=ps.find(x=>x.id===Number(m[1]));"
        "el.innerHTML=`<article><h1>${p?p.title:'404'}</h1><span id='route-tag'>${location.pathname}</span></article>`;}"
        "else{el.innerHTML=`<h1>首页(${ps.length})</h1>`;}})();"
    )
    js_v2 = js_v1 + "/*v2*/"
    css_v1 = "body{background-color:rgb(248, 250, 252);color:rgb(30, 41, 59);}"

    vercel_spa_cfg = {"rewrites": [{"source": "/(.*)", "destination": "/index.html"}]}
    vercel_no_rewrite = {"rewrites": []}
    vite_config_sample = "export default { base: '/', build: { outDir: 'dist', assetsDir: 'assets' } }"

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        dist1 = root / "dist1"
        dist2 = root / "dist2"
        js1_name, css1_name = build_dist(dist1, js_v1, css_v1, posts_bytes)
        js2_name, css2_name = build_dist(dist2, js_v2, css_v1, posts_bytes)
        public_copied_exact = (dist1 / "posts.json").read_bytes() == posts_bytes

        # .gitignore pattern check
        gitignore_lines = ["node_modules", "dist", ".DS_Store", "*.local"]
        def is_ignored(rel_path: str) -> bool:
            top = rel_path.split("/")[0]
            return top in gitignore_lines or any(
                pat.startswith("*.") and rel_path.endswith(pat[1:]) for pat in gitignore_lines
            )

        ignored_check = {
            "node_modules/vue/index.js": is_ignored("node_modules/vue/index.js"),
            "dist/index.html": is_ignored("dist/index.html"),
            "src/App.vue": is_ignored("src/App.vue"),
            "public/posts.json": is_ignored("public/posts.json"),
        }
        git_workflow = [
            "git init",
            "git add .",
            'git commit -m "初始化博客项目"',
            "git branch -M main",
            "git remote add origin https://github.com/<user>/blog-app.git",
            "git push -u origin main",
        ]

        # Test local preview with and without vercel.json SPA rewrite in Chromium
        srv_spa, port_spa = start_preview_server(dist1, vercel_spa_cfg)
        srv_raw, port_raw = start_preview_server(dist1, vercel_no_rewrite)
        try:
            with sync_playwright() as p:
                browser = launch_browser(p)
                try:
                    page = browser.new_page()
                    # Without SPA rewrite, direct /post/2 fails with 404
                    resp_raw = page.goto(f"http://127.0.0.1:{port_raw}/post/2")
                    raw_status = resp_raw.status

                    # With vercel.json SPA rewrite, direct /post/2 returns 200 and renders article 2 + hashed CSS
                    resp_spa = page.goto(f"http://127.0.0.1:{port_spa}/post/2")
                    spa_status = resp_spa.status
                    page.wait_for_selector("article h1")
                    spa_h1 = page.text_content("article h1")
                    spa_route = page.text_content("#route-tag")
                    body_bg = page.evaluate("getComputedStyle(document.body).backgroundColor")
                finally:
                    browser.close()
        finally:
            srv_spa.shutdown()
            srv_spa.server_close()
            srv_raw.shutdown()
            srv_raw.server_close()

    vercel_preset = {
        "Framework Preset": "Vite",
        "Build Command": "npm run build",
        "Output Directory": "dist",
        "Root Directory": "./",
    }
    domain_dns = {
        "free_suffix": ".vercel.app",
        "cname_target": "cname.vercel-dns.com",
        "vite_outdir_in_config": "outDir: 'dist'" in vite_config_sample,
    }

    actuals = {
        "vite_dist_hash_and_public_copy": {
            "js_hash_changed_on_edit": js1_name != js2_name,
            "css_hash_stable_when_unchanged": css1_name == css2_name,
            "js_matches_hash_pattern": bool(re.fullmatch(r"index-[0-9a-f]{8}\.js", js1_name)),
            "public_copied_exact": public_copied_exact,
        },
        "gitignore_and_git_push_checks": {
            "ignored_check": ignored_check,
            "git_step_count": len(git_workflow),
            "default_branch_cmd": git_workflow[3],
        },
        "vercel_spa_rewrite_preview_in_chromium": {
            "raw_direct_post_status": raw_status,
            "spa_rewrite_post_status": spa_status,
            "rendered_h1": spa_h1,
            "rendered_route": spa_route,
            "hashed_css_applied_bg": body_bg,
        },
        "vercel_preset_and_domain_config": {
            "preset": vercel_preset,
            "domain_dns": domain_dns,
        },
    }
    expected = {
        "vite_dist_hash_and_public_copy": {
            "js_hash_changed_on_edit": True,
            "css_hash_stable_when_unchanged": True,
            "js_matches_hash_pattern": True,
            "public_copied_exact": True,
        },
        "gitignore_and_git_push_checks": {
            "ignored_check": {
                "node_modules/vue/index.js": True,
                "dist/index.html": True,
                "src/App.vue": False,
                "public/posts.json": False,
            },
            "git_step_count": 6,
            "default_branch_cmd": "git branch -M main",
        },
        "vercel_spa_rewrite_preview_in_chromium": {
            "raw_direct_post_status": 404,
            "spa_rewrite_post_status": 200,
            "rendered_h1": "JS 异步编程详解",
            "rendered_route": "/post/2",
            "hashed_css_applied_bg": "rgb(248, 250, 252)",
        },
        "vercel_preset_and_domain_config": {
            "preset": {
                "Framework Preset": "Vite",
                "Build Command": "npm run build",
                "Output Directory": "dist",
                "Root Directory": "./",
            },
            "domain_dns": {
                "free_suffix": ".vercel.app",
                "cname_target": "cname.vercel-dns.com",
                "vite_outdir_in_config": True,
            },
        },
    }
    cases = [
        {"name": k, "expected": expected[k], "actual": actuals[k], "passed": actuals[k] == expected[k]}
        for k in expected
    ]
    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/vue3-blog-deploy-vercel-lab/explore-blog-deploy-vercel.py

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

下载课程关联工程包:Vue3

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

下载课程关联工程包:Vue3

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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