fix(build): vite部署问题,部署后有缓存取到旧的chunk文件

This commit is contained in:
sophie committed 2026-08-28 11:34:37 +08:00
1 parent 09deada712
commit 57652ae581
7 files changed
+62 -108

No files matched your search

+13
View File
@@ -14,6 +14,19 @@ server {
try_files $uri $uri/ /index.html;
}
# Vite 构建产物(/assets/ 下带 hash 文件):内容寻址,文件名一变即换新缓存,可放心长期 immutable 缓存。
location /assets/ {
root /usr/share/nginx/html;
add_header Cache-Control "public, max-age=31536000, immutable";
}
# index.html 必须始终重新校验(no-cache):避免浏览器/网关缓存旧版 HTML,引用部署后已删除的旧 hash 产物,
# 导致登录后懒加载 chunk 404,报 "Failed to fetch dynamically imported module"。
location = /index.html {
root /usr/share/nginx/html;
add_header Cache-Control "no-cache, no-store, must-revalidate";
}
# API 代理到后端
location /api/ {
# 通过 Docker 内置 DNS 动态解析后端服务,避免后端容器重建后
+22
View File
@@ -34,6 +34,26 @@ function resolveAppBaseTitle(): string {
return String(i18n.global.t(config.appTitleKey));
}
/**
* 懒加载 chunk 失败自愈。
* 用途/触发时机:部署后若浏览器(或网关)缓存了旧版 index.html,会引用已删除的旧 hash 产物,
* 登录等页面跳转时动态 import() 该 chunk 失败 → 报 "Failed to fetch dynamically imported module"
* 并被登录流程误判为“登录失败”。此处检测到该类失败时做一次整页刷新(带 sessionStorage 防循环守卫),
* 刷新后取到最新 index.html 与 chunk,用户即可正常进入,不再看到误导性报错。
* 核心逻辑:仅匹配 chunk 加载失败错误;同一标签页会话内只刷新一次,避免服务器持续异常时无限刷新。
* @param router - Vue Router 实例
*/
function setupChunkLoadRecovery(router: Router): void {
router.onError((error) => {
const message = String((error as Error)?.message || '');
if (!message.includes('Failed to fetch dynamically imported module')) return;
const recoveryKey = 'hxops_chunk_load_recovery_once';
if (sessionStorage.getItem(recoveryKey)) return;
sessionStorage.setItem(recoveryKey, '1');
window.location.reload();
});
}
export function setupRouterGuards(router: Router): void {
router.beforeEach((to, _from, next) => {
const auth = useAuthStore();
@@ -69,4 +89,6 @@ export function setupRouterGuards(router: Router): void {
const pageTitle = resolveRouteTitle(to.meta.title);
document.title = pageTitle ? `${pageTitle} - ${baseTitle}` : baseTitle;
});
setupChunkLoadRecovery(router);
}