蓝色天空.知识 · 实践 · 创造
我的收藏
Vue3 教程目录 48章
Vue3 / LEARN BY DOING

打包上线

核对 Vite 生产构建 dist/ 产物特征与哈希缓存、GitHub 推送与 .gitignore 规范、Vercel 零配置自动部署与 SPA 重写规则实测、自定义域名 CNAME 及 Vue 3 进阶路线。

学完这一章,你能够

  • 核对 Vite 生产构建 dist/ 产物特征与哈希缓存、GitHub 推送与 .gitignore 规范、Vercel 零配置自动部署与 SPA 重写规则实测、自定义域名 CNAME 及 Vue 3 进阶路线。

Vite 生产构建产物特征与本地预览

开发阶段使用 `npm run dev` 启动支持热模块替换(HMR)的开发服务器;而上线前需执行 `npm run build` 生成面向生产环境优化的 `dist/` 静态产物目录。构建产物包含四项关键特性:入口 `index.html` 自动重写为打包后资源路径,JS/CSS 文件名附带内容哈希(如 `index-Df3aBc9x.js`)以精准控制浏览器长效缓存;业务代码经过压缩与 Tree-shaking 移除死代码;JS 与 CSS 拆分为独立静态资源;`public/` 下的 `posts.json`、`favicon.ico` 等文件不经编译原样复制到 `dist/` 根目录。打包后可在本地执行 `npx vite preview` 模拟生产环境预览。本站离线实测模拟生产构建:修改 JS 源码后产物哈希文件名随即变更而未改动的 CSS 哈希保持稳定,`index-[0-9a-f]{8}.js` 格式校验通过,且 `dist/posts.json` 与源文件逐字节一致。

推送代码到 GitHub 与 .gitignore 检查

现代静态托管平台(如 Vercel)通常直接对接 Git 仓库自动拉取并构建。首先在 GitHub 新建名为 `blog-app` 的 Public 仓库(不要勾选自动初始化 README,以免与本地历史冲突);接着在项目目录依次执行 `git init`、`git add .`、`git commit -m "初始化博客项目"`、`git branch -M main`、`git remote add origin ...` 与 `git push -u origin main` 完成首次推送。推送前务必确认 `.gitignore` 已排除 `node_modules`(可由 `npm install` 还原)和 `dist`(应由部署平台按最新源码重新构建)。本站实测验证 `.gitignore` 规则准确拦截 `node_modules/vue/index.js` 与 `dist/index.html`,同时保留跟踪 `src/App.vue` 与 `public/posts.json`。

Vercel 零配置部署、SPA 路由重写与自动上线

使用 GitHub 账号登录 `vercel.com` 后,点击 `New Project` 导入 `blog-app` 仓库,Vercel 会自动识别 `Framework Preset: Vite`、`Build Command: npm run build`、`Output Directory: dist` 与 `Root Directory: ./`,无需额外配置即可点击 `Deploy` 获得形如 `https://blog-app.vercel.app` 的公网访问地址。后续每次执行 `git push` 提交新代码,平台会自动触发监听提交、安装依赖、执行构建与发布上线的全流程。若博客采用 HTML5 History 路由(`/post/:id`),需在项目根目录提供 `vercel.json` 的 SPA 重写规则(`rewrites: [{ "source": "/(.*)", "destination": "/index.html" }]`)防止直接刷新子路径出现 404。本站离线 Chromium 在本地回环静态服务器上对比实测:未启用 SPA 重写时直接访问 `/post/2` 返回 HTTP `404`;启用 `vercel.json` 重写后返回 HTTP `200`,成功加载带哈希 CSS(背景色 `rgb(248, 250, 252)`)与 `/posts.json` 并渲染文章标题 `JS 异步编程详解`。

自定义域名绑定与 Vue 3 下一步进阶路线

除免费 `.vercel.app` 子域名外,可在 Vercel 项目 `Settings → Domains` 填入自有域名(如 `blog.example.com`),按指引在 DNS 服务商处添加指向 `cname.vercel-dns.com` 的 CNAME 记录,待解析生效后平台会自动签发并续期 HTTPS/SSL 证书。完成本博客实战后,可根据目标向四个方向进阶:使用 TypeScript 强化大型项目 props/store 类型安全、借助 Nuxt.js 实现服务端渲染与 SEO、引入 VueUse 复用 200+ 成熟组合式函数,或搭配 Element Plus / Naive UI / Ant Design Vue 快速构建中后台系统。

Vercel 导入 Vite/Vue 项目自动检测配置项

配置项默认值说明
Framework Preset(框架预设)Vite导入仓库后由平台自动检测识别
Build Command(构建命令)npm run build自动执行 package.json 中的生产打包脚本
Output Directory(输出目录)dist部署 Vite 默认生成的静态构建产物目录
Root Directory(项目根目录)./默认仓库根目录(多包仓库可手动指定子目录)

Vue 3 核心技能掌握后的进阶学习路线

学习方向适用开发者推荐实践起点
TypeScript + Vue 3需要构建中大型、强类型约束工程的开发者优先为 defineProps、defineEmits 与 Pinia Store 补齐类型标注
Nuxt.js 全栈框架对搜索引擎优化(SEO)或首屏 SSR 有明确需求的项目体验基于文件系统的约定式路由与自动服务端渲染能力
VueUse 组合式工具库希望直接复用成熟高质量 Composables 的开发者按需引入内置 200+ 常用浏览器与状态组合式函数
成熟 UI 组件库需要快速交付企业管理后台或复杂表单页面的团队按设计风格选用 Element Plus、Naive UI 或 Ant Design Vue

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

含完整源码 · 253 行
展开查看收起
python
"""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()
核对修改 JS 变更文件哈希而 CSS 哈希不变、public/posts.json 原样复制、.gitignore 排除 node_modules 与 dist,以及未配 SPA 重写访问 /post/2 得 404 而配置后返回 200 并渲染正文。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a801.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Vue3

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

下载课程关联工程包:Vue3

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

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

内容哈希允许浏览器和 CDN 对静态资源设置长期强缓存,文件内容不变则命中缓存、一旦重新打包修改代码则文件名变更自动失效旧缓存;History 模式下直接刷新 /post/2 会向托管服务器请求该路径,服务端若无对应静态文件将返回 404,必须通过 rewrite 回退到 /index.html 交由前端路由接管。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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