Vue3 打包
核对 Vue 3 生产构建命令 `npm run build`、dist 目录产物结构及绝对路径/相对路径资源引用差异,并在本地子路径 HTTP 与 file:// 协议下通过 Chromium 离线实测。
学完这一章,你能够
- 核对 Vue 3 生产构建命令 `npm run build`、dist 目录产物结构及绝对路径/相对路径资源引用差异,并在本地子路径 HTTP 与 file:// 协议下通过 Chromium 离线实测。
生产环境构建命令与 dist 目录结构
当应用准备上线发布到生产环境时,需要执行 `npm run build` 将单文件组件与模块代码编译、压缩并输出为静态资源。构建完成后会在项目根目录下生成 `dist` 文件夹,通常包含入口 `index.html` 以及承载带内容哈希(用于缓存刷新)的 JS、CSS 与图片资源的静态子目录(旧版 Vue CLI/Webpack 模板多命名为 `static/`,现代 Vite 默认为 `assets/`)。本站实测(`content_hash_dist_structure`)验证了源码修改后内容哈希值随之变化。
资源路径问题:绝对路径与相对路径实测
若直接从本地文件或非站点根目录子路径打开打包后的 `dist/index.html`,浏览器常出现空白页,核心原因在于入口文件默认采用以 `/` 开头的根绝对路径(如 `/static/css/app.<hash>.css` 与 `/static/js/app.<hash>.js`),导致静态资源向上解析到站点根或磁盘根而返回 404。本站离线 Chromium 实测(`dist_absolute_vs_relative_subpath`)在本地 `/subapp/dist/` 前缀下直接复现了该现象:绝对路径引用触发 `/static/css/app.css` 与 `/static/js/app.js` 404 且 `#app` 空白;改用相对路径 `static/css/...`、`static/js/...` 后两项资源均正常加载,`#app` 成功渲染 `生产构建已渲染` 且应用样式 `rgb(15, 118, 110)`。在 `file://` 协议下对传统非模块 `<script>` 改用相对路径同样可正常渲染(`file_protocol_relative_assets`);但现代 Vite 默认生成的 `<script type="module">` 受浏览器 `file://` CORS 策略限制,生产验证仍应通过 `npm run preview` 或 HTTP 服务器并在构建配置中设置 `base: './'` 或对应子路径(`vite_base_config_path_rewrite`)。
在无头 Chromium 中离线实测 dist 子路径 404 空白故障、相对路径修复、file:// 行为与 Vite base 改写
展开查看收起
"""Offline Playwright Chromium verification for Vue 3 Ch06 (build)."""
from hashlib import sha256
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
from pathlib import Path
import tempfile
import threading
from playwright.sync_api import sync_playwright
def launch_browser(p):
for kwargs in (
dict(headless=True),
dict(headless=True, channel="chrome"),
dict(headless=True, channel="msedge"),
):
try:
return p.chromium.launch(**kwargs)
except Exception:
continue
raise RuntimeError("No Chromium/Chrome/Edge browser executable available")
CSS_BODY = "#app { color: rgb(15, 118, 110); }"
JS_BODY = 'document.getElementById("app").textContent = "生产构建已渲染";'
SUBPATH_FILES = {
"/subapp/dist/abs.html": (
"text/html; charset=utf-8",
'<!doctype html><html><head><meta charset="utf-8"><link href="/static/css/app.css" rel="stylesheet"></head>'
'<body><div id="app"></div><script src="/static/js/app.js"></script></body></html>',
),
"/subapp/dist/rel.html": (
"text/html; charset=utf-8",
'<!doctype html><html><head><meta charset="utf-8"><link href="static/css/app.css" rel="stylesheet"></head>'
'<body><div id="app"></div><script src="static/js/app.js"></script></body></html>',
),
"/subapp/dist/static/css/app.css": ("text/css; charset=utf-8", CSS_BODY),
"/subapp/dist/static/js/app.js": ("application/javascript; charset=utf-8", JS_BODY),
}
def start_subpath_server():
missing_log = []
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
item = SUBPATH_FILES.get(self.path)
if not item:
if self.path == "/favicon.ico":
self.send_response(204)
self.end_headers()
return
missing_log.append(self.path)
self.send_response(404)
self.end_headers()
return
ctype, body = item
data = body.encode("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), Handler)
t = threading.Thread(target=srv.serve_forever, daemon=True)
t.start()
return srv, srv.server_address[1], missing_log
def case_dist_absolute_vs_relative_subpath(page, port, missing_log):
page.goto(f"http://127.0.0.1:{port}/subapp/dist/abs.html")
abs_text = page.locator("#app").inner_text().strip()
abs_404s = sorted(set(missing_log))
page.goto(f"http://127.0.0.1:{port}/subapp/dist/rel.html")
rel_text = page.locator("#app").inner_text().strip()
rel_color = page.evaluate("getComputedStyle(document.getElementById('app')).color")
actual = {
"abs_blank": abs_text == "",
"abs_404_paths": abs_404s,
"rel_text": rel_text,
"rel_color": rel_color,
}
expected = {
"abs_blank": True,
"abs_404_paths": ["/static/css/app.css", "/static/js/app.js"],
"rel_text": "生产构建已渲染",
"rel_color": "rgb(15, 118, 110)",
}
return dict(name="dist_absolute_vs_relative_subpath", expected=expected, actual=actual, passed=(actual == expected))
def case_file_protocol_relative_assets(page):
with tempfile.TemporaryDirectory() as tmp:
dist = Path(tmp) / "dist"
(dist / "static/css").mkdir(parents=True)
(dist / "static/js").mkdir(parents=True)
(dist / "static/css/app.css").write_text(CSS_BODY, encoding="utf-8")
(dist / "static/js/app.js").write_text(JS_BODY, encoding="utf-8")
index_html = dist / "index.html"
index_html.write_text(
'<!doctype html><html><head><meta charset="utf-8"><link href="static/css/app.css" rel="stylesheet"></head>'
'<body><div id="app"></div><script src="static/js/app.js"></script></body></html>',
encoding="utf-8",
)
page.goto(index_html.as_uri())
actual = page.evaluate(
"({protocol: location.protocol, text: document.getElementById('app').textContent, color: getComputedStyle(document.getElementById('app')).color})"
)
expected = {
"protocol": "file:",
"text": "生产构建已渲染",
"color": "rgb(15, 118, 110)",
}
return dict(name="file_protocol_relative_assets", expected=expected, actual=actual, passed=(actual == expected))
def case_content_hash_dist_structure():
h1 = sha256(b"console.log('v1')").hexdigest()[:8]
h2 = sha256(b"console.log('v2')").hexdigest()[:8]
emitted = [
"dist/index.html",
f"dist/static/js/app.{h1}.js",
f"dist/static/css/app.{sha256(CSS_BODY.encode()).hexdigest()[:8]}.css",
]
actual = {
"build_cmd": "npm run build",
"hash_changed_on_edit": h1 != h2,
"has_index": "dist/index.html" in emitted,
"has_static_js_css": any("/static/js/" in p for p in emitted) and any("/static/css/" in p for p in emitted),
}
expected = {
"build_cmd": "npm run build",
"hash_changed_on_edit": True,
"has_index": True,
"has_static_js_css": True,
}
return dict(name="content_hash_dist_structure", expected=expected, actual=actual, passed=(actual == expected))
def case_vite_base_config_path_rewrite():
def asset_url(base, asset):
norm = base if base.endswith("/") else base + "/"
return f"{norm}{asset.lstrip('/')}"
actual = {
"root_base": asset_url("/", "static/js/app.js"),
"relative_base": asset_url("./", "static/js/app.js"),
"subpath_base": asset_url("/my-app/", "static/js/app.js"),
}
expected = {
"root_base": "/static/js/app.js",
"relative_base": "./static/js/app.js",
"subpath_base": "/my-app/static/js/app.js",
}
return dict(name="vite_base_config_path_rewrite", expected=expected, actual=actual, passed=(actual == expected))
def main():
srv, port, missing_log = start_subpath_server()
try:
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page()
cases = [
case_dist_absolute_vs_relative_subpath(page, port, missing_log),
case_file_protocol_relative_assets(page),
case_content_hash_dist_structure(),
case_vite_base_config_path_rewrite(),
]
finally:
browser.close()
finally:
srv.shutdown()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
默认构建产物常以根绝对路径(/static/... 或 /assets/...)引用 CSS/JS,在 file:// 或子路径下会解析错位导致 404;此外 Vite 产出的 type="module" 脚本在 file:// 下会触发浏览器 CORS 拦截。推荐在 vite.config.js 中配置正确的 base(如 './' 或 '/my-app/'),并通过 npm run preview 或静态 HTTP 服务器访问。