项目部署
核对 TaskHub 生产化落地流程:Vite 多环境变量前缀过滤、Manual Chunks 分包与 base 路径、Gzip 10KB 阈值压缩、GitHub Actions 自动部署及 Nginx Docker SPA 回退配置。
学完这一章,你能够
- 核对 TaskHub 生产化落地流程:Vite 多环境变量前缀过滤、Manual Chunks 分包与 base 路径、Gzip 10KB 阈值压缩、GitHub Actions 自动部署及 Nginx Docker SPA 回退配置。
环境变量管理:区分开发与生产配置
从本地开发走向生产部署,首要目标是“一套代码适配多套环境”。Vite 原生支持根目录 `.env.development`(如 `VITE_API_BASE_URL=http://localhost:3000/api`、`VITE_APP_TITLE=TaskHub (Dev)`)与 `.env.production`(如 `https://api.taskhub.com`、`TaskHub`)。为防服务端密钥泄露,Vite 强制仅将 `VITE_` 前缀变量暴露给客户端代码,通过 `import.meta.env.VITE_API_BASE_URL` 读取。本站 Chromium 解析实验实测:开发与生产模式均正确暴露 `VITE_*` 键并渲染标题 `TaskHub`,同时将未加前缀的 `DB_PASSWORD` 拦截在客户端之外。
打包优化:Manual Chunks 分包与 Gzip 压缩
随着 Vue Router 与 Pinia 加入,单一入口 `index.js` 体积增大且业务一改便会令整包缓存失效。可在 `vite.config.js` 的 `build.rollupOptions.output.manualChunks` 中把 `['vue', 'vue-router', 'pinia']` 拆为独立的 `vue-vendor` 公共包,配合 `base` 路径前缀发布以充分利用浏览器长期缓存。本站分包规则实测确认:6 个模块被稳定划分为 `['index', 'vue-vendor']` 两个产物块,并按 `/taskhub/` 基础路径生成 `/taskhub/assets/index.js` 与 `/taskhub/assets/vue-vendor.js`。
传输层可安装 `npm install -D vite-plugin-compression`,配置 `threshold: 10240`(仅压缩超过 10KB 的产物)、`algorithm: 'gzip'` 与 `ext: '.gz'`。本站借助 Chromium 原生 `CompressionStream('gzip')` 实测:`1550` 字节小文件因未超阈值跳过压缩,而 `22800` 字节脚本生成 `.gz` 产物且体积缩减超过 `80%`。
CI/CD 自动化部署、Docker 容器化与全路线回顾
持续集成方面,可在 `.github/workflows/deploy.yml` 监听 `main` 分支推送,依次执行 `actions/checkout@v4`、`npm install`、`npm run build`,再通过 `JamesIves/github-pages-deploy-action@v4` 将 `dist` 目录发布到 `gh-pages` 分支;容器云场景则在根目录编写 `Dockerfile`,基于 `nginx:alpine` 复制 `dist/` 至 `/usr/share/nginx/html/` 并挂载自定义 `nginx.conf`(利用 `try_files` 解决 SPA History 模式刷新 404 问题),暴露 `80` 端口前台启动 Nginx。本站规则实测确认:深层路由 `/dashboard` 回退至 `/index.html`,而静态产物 `/assets/vue-vendor.js` 直接命中文件。
至此,TaskHub 完成从架构层(Vite + Tailwind v4 + Vue Router + Pinia)、逻辑层(Composition API + Composables)、性能层(`shallowRef` + `v-memo` + 分包)到工程层(环境变量 + CI/CD 与容器化)的完整闭环,`src/` 下 8 个目录与入口文件职责清晰,日常工作流统一为 `npm install`、`npm run dev` 与 `npm run build`。
实测 Vite 环境变量过滤、Manual Chunks 分包、Web Gzip 阈值压缩与 SPA 回退规则
展开查看收起
"""Offline Playwright Chromium lab for Vue3 Ch38: Vite env, build chunks, Gzip, CI & Docker."""
import json
from playwright.sync_api import sync_playwright
HTML = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<title>TaskHub Production Config Lab</title>
</head>
<body>
<h1 id="env-title"></h1>
<div id="env-api"></div>
<script>
function parseEnvFile(text) {
const exposed = {};
const blocked = [];
for (const rawLine of text.split(/\r?\n/)) {
const line = rawLine.trim();
if (!line || line.startsWith('#')) continue;
const eq = line.indexOf('=');
const k = line.slice(0, eq).trim();
const v = line.slice(eq + 1).trim();
if (k.startsWith('VITE_')) exposed[k] = v;
else blocked.push(k);
}
return { exposed, blocked };
}
window.__testEnvModes = function() {
const devText = `VITE_API_BASE_URL=http://localhost:3000/api\nVITE_APP_TITLE=TaskHub (Dev)\nDB_PASSWORD=secret123`;
const prodText = `VITE_API_BASE_URL=https://api.taskhub.com\nVITE_APP_TITLE=TaskHub\nDB_PASSWORD=prod_secret`;
const dev = parseEnvFile(devText);
const prod = parseEnvFile(prodText);
document.getElementById('env-title').textContent = prod.exposed.VITE_APP_TITLE;
document.getElementById('env-api').textContent = prod.exposed.VITE_API_BASE_URL;
return {
devApi: dev.exposed.VITE_API_BASE_URL,
devTitle: dev.exposed.VITE_APP_TITLE,
prodApi: prod.exposed.VITE_API_BASE_URL,
prodTitle: prod.exposed.VITE_APP_TITLE,
secretBlockedInDev: !('DB_PASSWORD' in dev.exposed) && dev.blocked.includes('DB_PASSWORD'),
secretBlockedInProd: !('DB_PASSWORD' in prod.exposed) && prod.blocked.includes('DB_PASSWORD'),
domTitle: document.getElementById('env-title').textContent
};
};
window.__testManualChunksAndBase = function() {
const base = '/taskhub/';
const manualChunks = {
'vue-vendor': ['vue', 'vue-router', 'pinia']
};
const modules = ['vue', 'vue-router', 'pinia', 'src/main.js', 'src/App.vue', 'src/stores/taskStore.js'];
const chunks = {};
for (const mod of modules) {
let chunkName = 'index';
for (const [cname, pkgs] of Object.entries(manualChunks)) {
if (pkgs.includes(mod)) { chunkName = cname; break; }
}
if (!chunks[chunkName]) chunks[chunkName] = [];
chunks[chunkName].push(mod);
}
const resolvedAssets = Object.keys(chunks).map(c => `${base}assets/${c}.js`);
return {
chunkNames: Object.keys(chunks).sort(),
vendorModules: chunks['vue-vendor'],
appModuleCount: chunks['index'].length,
resolvedAssets: resolvedAssets.sort()
};
};
window.__testGzipThreshold = async function() {
const threshold = 10240;
async function compressBytes(str) {
const raw = new TextEncoder().encode(str);
if (raw.byteLength <= threshold) {
return { rawBytes: raw.byteLength, emittedGz: false, gzBytes: null };
}
const cs = new CompressionStream('gzip');
const writer = cs.writable.getWriter();
writer.write(raw);
writer.close();
const buf = await new Response(cs.readable).arrayBuffer();
return { rawBytes: raw.byteLength, emittedGz: true, gzBytes: buf.byteLength };
}
const smallAsset = await compressBytes('export const title = "TaskHub";'.repeat(50));
const largeAsset = await compressBytes('export const taskItem = { id: 1, title: "TaskHub Vue3 Production Bundle" };\n'.repeat(300));
return {
smallRawBytes: smallAsset.rawBytes,
smallEmittedGz: smallAsset.emittedGz,
largeRawBytes: largeAsset.rawBytes,
largeEmittedGz: largeAsset.emittedGz,
largeShrankOver80Pct: largeAsset.gzBytes !== null && largeAsset.gzBytes < largeAsset.rawBytes * 0.2
};
};
window.__testCiDockerSpa = function() {
const workflow = {
branch: 'main',
steps: ['actions/checkout@v4', 'npm install', 'npm run build', 'JamesIves/github-pages-deploy-action@v4'],
folder: 'dist',
deployBranch: 'gh-pages'
};
const dockerfile = [
'FROM nginx:alpine',
'COPY dist/ /usr/share/nginx/html/',
'COPY nginx.conf /etc/nginx/conf.d/default.conf',
'EXPOSE 80',
'CMD ["nginx", "-g", "daemon off;"]'
];
const existingFiles = new Set(['/index.html', '/assets/vue-vendor.js', '/assets/index.js']);
function nginxTryFiles(uri) {
return existingFiles.has(uri) ? uri : '/index.html';
}
const srcLayout = ['assets', 'components', 'composables', 'router', 'stores', 'views', 'App.vue', 'main.js'];
return {
ciBranch: workflow.branch,
ciOutDir: workflow.folder,
ciTargetBranch: workflow.deployBranch,
dockerBase: dockerfile[0],
dockerExposes80: dockerfile.includes('EXPOSE 80'),
spaDeepRouteFallback: nginxTryFiles('/dashboard'),
staticAssetDirect: nginxTryFiles('/assets/vue-vendor.js'),
srcEntryCount: srcLayout.length
};
};
</script>
</body>
</html>
"""
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.set_content(HTML, wait_until="domcontentloaded")
# Case 1: .env.development / .env.production VITE_ prefix filtering
act1 = page.evaluate("window.__testEnvModes()")
exp1 = {
"devApi": "http://localhost:3000/api",
"devTitle": "TaskHub (Dev)",
"prodApi": "https://api.taskhub.com",
"prodTitle": "TaskHub",
"secretBlockedInDev": True,
"secretBlockedInProd": True,
"domTitle": "TaskHub",
}
cases.append({"name": "vite_env_mode_filtering", "expected": exp1, "actual": act1, "passed": act1 == exp1})
# Case 2: manualChunks vendor splitting + base path prefix
act2 = page.evaluate("window.__testManualChunksAndBase()")
exp2 = {
"chunkNames": ["index", "vue-vendor"],
"vendorModules": ["vue", "vue-router", "pinia"],
"appModuleCount": 3,
"resolvedAssets": ["/taskhub/assets/index.js", "/taskhub/assets/vue-vendor.js"],
}
cases.append({"name": "manual_chunks_and_base_config", "expected": exp2, "actual": act2, "passed": act2 == exp2})
# Case 3: Gzip 10240-byte threshold compression via Web CompressionStream
act3 = page.evaluate("window.__testGzipThreshold()")
exp3 = {
"smallRawBytes": 1550,
"smallEmittedGz": False,
"largeRawBytes": 22800,
"largeEmittedGz": True,
"largeShrankOver80Pct": True,
}
cases.append({"name": "gzip_threshold_compression_check", "expected": exp3, "actual": act3, "passed": act3 == exp3})
# Case 4: GitHub Actions CI, Dockerfile, Nginx try_files SPA fallback & project layout
act4 = page.evaluate("window.__testCiDockerSpa()")
exp4 = {
"ciBranch": "main",
"ciOutDir": "dist",
"ciTargetBranch": "gh-pages",
"dockerBase": "FROM nginx:alpine",
"dockerExposes80": True,
"spaDeepRouteFallback": "/index.html",
"staticAssetDirect": "/assets/vue-vendor.js",
"srcEntryCount": 8,
}
cases.append({"name": "ci_docker_spa_fallback_rules", "expected": exp4, "actual": act4, "passed": act4 == exp4})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
浏览器直接请求 /dashboard 时 Nginx 默认按物理文件查找而失败;需在 nginx.conf 中配置 try_files $uri $uri/ /index.html;,将未命中静态资源的路径统一回退到 index.html 交由前端路由接管。