打包上线
核对 Vite 生产构建 dist/ 产物特征(内容哈希、压缩与 Tree-shaking、public 原样复制)、GitHub 推送与 .gitignore 规范、Vercel 零配置自动部署与 SPA 重写实测,以及 React 进阶学习路线。
学完这一章,你能够
- 核对 Vite 生产构建 dist/ 产物特征(内容哈希、压缩与 Tree-shaking、public 原样复制)、GitHub 推送与 .gitignore 规范、Vercel 零配置自动部署与 SPA 重写实测,以及 React 进阶学习路线。
构建优化后的生产包 dist/ 与本地预览
开发阶段通过 `npm run dev` 启动支持热更新的 Vite 开发服务器,而线上发布需运行 `npm run build` 生成优化后的 `dist/` 静态产物目录。生产包具备三项关键优化:一是构建出的 JS/CSS 文件名附带内容哈希(内容变化即更新哈希,便于配置长效强缓存而不命中旧版);二是对源码完成压缩混淆与 Tree-shaking(剔除未引用的死代码);三是将 `public/` 下的 `posts.json`、`favicon.svg` 等静态文件原样复制到 `dist/` 根目录。构建完成后可运行 `npx vite preview` 在本地以生产模式预览验证。本站离线构建产物实测生成 `index-08b86c91.js` 与 `index-bb9c7abe.css`,源码微调后哈希立即变更、未使用的 `unusedDebugHelper` 已被剔除且产物体积更小,`dist/` 根目录完整保留 `['favicon.svg', 'index.html', 'posts.json']`。
推送代码到 GitHub 与 .gitignore 核查
托管源码需先在 GitHub 新建名为 `react-blog-app` 的 Public 仓库(不勾选 Initialize with README 避免提交历史冲突),再进入 `blog-app` 目录依次执行 `git init`、`git add .`、`git commit -m "初始化 React 博客项目"`、`git branch -M main`、`git remote add origin <仓库地址>` 与 `git push -u origin main`。推送前务必检查 `.gitignore` 已忽略 `node_modules`(依赖可由 `npm install` 还原)和 `dist`(由部署平台自动构建生成)。本站规则校验确认 `node_modules/react/index.js` 与 `dist/index.html` 被准确忽略,而 `src/App.jsx`、`package.json`、`public/posts.json` 保持纳入版本控制。
Vercel 零配置自动部署、SPA 路由重写与自定义域名
登录 vercel.com 授权 GitHub 账号后,点击 New Project 导入 `react-blog-app` 仓库,平台会自动识别 `Framework Preset: Vite`、`Build Command: npm run build` 与 `Output Directory: dist`,点击 Deploy 即可获得公开访问地址(如 `https://react-blog-app.vercel.app`)。此后每次执行 `git push`,平台会自动触发“拉取源码 → `npm install` → `npm run build` → 发布上线”的持续部署流水线。
若需绑定自定义域名,可在项目 Settings → Domains 添加域名(如 `blog.example.com`),在 DNS 服务商处配置指向 `cname.vercel-dns.com` 的 CNAME 记录,待解析生效后平台将自动签发 SSL 证书。此外,对于使用 `createBrowserRouter` 的单页应用,上线时常需配置 `vercel.json` 将任意深链接重写到 `/index.html`。本站离线 Chromium 搭建本地生产预览服务器实测:未开启 SPA 重写时直接访问 `/post/2` 返回 HTTP `404`;启用重写规则后直接访问 `/post/2` 返回 HTTP `200`,浏览器成功加载带哈希的 JS/CSS 与 `/posts.json` 并渲染文章标题 `JavaScript 异步编程详解`(`.post-view` 最大宽度 `720px`);同时核对带哈希静态资源响应头为 `public, max-age=31536000, immutable`,而入口 `index.html` 为 `no-cache`。
React 进阶学习方向与生态路线对照
完成从零搭建到打包上线的完整 React 博客项目后,你已掌握状态驱动视图、组件化拆分与单向数据流核心心智模型。后续可按项目诉求逐步叠加维度:引入 TypeScript 强化 Props 与 Hook 类型约束;采用 Next.js 构建具备 SSR、SEO 与全栈能力的应用;借助 TanStack Query(React Query)处理服务端缓存、自动重试与乐观更新;复杂全局状态可选用轻量 Zustand 或 Redux Toolkit;后台中台场景可结合 Ant Design、MUI 或 shadcn/ui 提升交付效率。
Vercel 导入 Vite React 项目的自动检测构建配置
| 构建配置项 | 自动填充值 | 说明 |
| Framework Preset | Vite | 平台依据 package.json 与配置自动识别 |
| Build Command | npm run build | 自动执行 Vite 生产打包命令 |
| Output Directory | dist | 自动发布 Vite 产出的静态资源目录 |
React 完成首个实战项目后的进阶学习方向
| 进阶方向 | 适用人群与诉求 | 推荐切入点 |
| TypeScript + React | 需要更强静态类型保障的中大型项目 | 从为组件 Props 与自定义 Hook 补充类型定义入手 |
| Next.js | 关注 SEO、服务端渲染(SSR)与全栈接口 | 基于 React 的全栈框架,掌握文件系统路由与服务端组件 |
| React Query (TanStack Query) | 接口请求复杂、需要缓存与状态同步 | 重点掌握请求缓存、自动重取与乐观更新机制 |
| 专业状态管理库 | 跨模块业务状态非常庞大 | 轻量选 Zustand,大型规范化团队选 Redux Toolkit |
| 成熟 UI 组件库 | 希望快速交付中后台与设计规范一致的界面 | 按设计风格选用 Ant Design、MUI 或 shadcn/ui |
React 生态与 Vue 3 生态主流全栈技术路线对照
| 技术领域 | React 生态代表 | Vue 3 生态代表 |
| SSR / 全栈框架 | Next.js | Nuxt.js |
| 静态类型支持 | TypeScript(原生 TSX 生态成熟) | TypeScript |
| 轻量状态管理 | Zustand | Pinia |
| 服务端状态与请求库 | React Query | VueUse / TanStack Query |
| 跨平台原生移动开发 | React Native | —(Weex 已停更) |
离线 Chromium 实测 dist 内容哈希产物、.gitignore 过滤与本地 SPA 重写深链接渲染
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
带内容哈希的静态资源内容一旦改动文件名就会变化,因此可以安全配置长效强缓存(`immutable`)加速回访加载;`index.html` 作为入口负责指向最新哈希资源清单,设为 `no-cache` 可确保浏览器每次校验入口是否更新,避免加载到旧版资源。