"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/vue3-taskhub-production-lab/explore-taskhub-production.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-taskhub-production.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a801.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a835.zip