/** * 部署后旧 chunk 会被新镜像替换:正在运行的旧页面再去 `import()` 已删除的分片时, * 浏览器只会抛一个 `Failed to fetch dynamically imported module`,React 拿不到任何内容。 * 这类错误只需要刷新一次页面即可恢复,其余错误交给错误边界展示。 */ const CHUNK_RELOAD_STORAGE_KEY = 'order-site-chunk-reload-at' /** 自动刷新防抖窗口:窗口内再次失败就展示错误页,避免无限刷新。 */ export const CHUNK_RELOAD_GUARD_MS = 30_000 const CHUNK_ERROR_HINTS = [ 'failed to fetch dynamically imported module', 'error loading dynamically imported module', 'importing a module script failed', 'chunkloaderror', 'loading chunk', 'load failed', ] /** 判断错误是否来自「动态 import 的分片加载失败」。 */ export function isChunkLoadError(error: unknown): boolean { if (error === null || error === undefined) return false const message = readErrorMessage(error).toLowerCase() return CHUNK_ERROR_HINTS.some((hint) => message.includes(hint)) } /** 兼容 Error 实例,以及 webpack/监控上报里常见的 { name, message } 普通对象。 */ function readErrorMessage(error: unknown): string { if (error instanceof Error) return `${error.name}: ${error.message}` if (typeof error === 'object') { const record = error as { name?: unknown; message?: unknown } const name = String(record.name || '') const message = String(record.message || '') if (name || message) return `${name}: ${message}` } return String(error) } /** * 判断本次分片失败是否允许自动刷新;允许时同时记录本次尝试时间。 * * 用 sessionStorage 而不是 localStorage:刷新只针对当前标签页里的旧版本页面, * 新开的标签页本来就拿到新 index.html,不需要继承这个窗口。 */ export function shouldAutoReloadChunkFailure( storage: Pick | null | undefined, now = Date.now(), ): boolean { if (!storage) return false try { const lastAttemptAt = Number(storage.getItem(CHUNK_RELOAD_STORAGE_KEY) || 0) if ( Number.isFinite(lastAttemptAt) && lastAttemptAt > 0 && now - lastAttemptAt < CHUNK_RELOAD_GUARD_MS ) { return false } storage.setItem(CHUNK_RELOAD_STORAGE_KEY, String(now)) return true } catch { // 隐私模式/存储被禁用时宁可展示错误页,也不要冒无限刷新的风险。 return false } }