feat: add lazyWithRetry for chunk load failure recovery

This commit is contained in:
ashim-hq
2026-04-20 21:56:08 +08:00
parent 1ad916448a
commit d40d7b3847
2 changed files with 76 additions and 0 deletions
+34
View File
@@ -0,0 +1,34 @@
import { type ComponentType, lazy } from "react";
function isChunkError(error: unknown): boolean {
if (!(error instanceof Error)) return false;
const msg = error.message.toLowerCase();
return (
msg.includes("dynamically imported module") ||
msg.includes("loading chunk") ||
msg.includes("loading css chunk") ||
msg.includes("failed to fetch")
);
}
export async function retryDynamicImport<T>(
importFn: () => Promise<T>,
retries = 3,
delay = 1000,
): Promise<T> {
for (let attempt = 1; attempt <= retries; attempt++) {
try {
return await importFn();
} catch (error) {
if (!isChunkError(error) || attempt === retries) throw error;
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
throw new Error("unreachable");
}
export function lazyWithRetry<T extends ComponentType<unknown>>(
importFn: () => Promise<{ default: T }>,
): React.LazyExoticComponent<T> {
return lazy(() => retryDynamicImport(importFn));
}