-
Notifications
You must be signed in to change notification settings - Fork 1
Open
Labels
Description
react 组件异步加载过程中,可能会由于页面部署原因导致 chunk 加载失败,从而导致整体页面报错,此处加上自动刷新页面的功能,可以解决此问题
同时可以让本地开发的过程中更加顺畅
import React, { lazy } from 'react';
const BASE_REFRESH_KEY = 'FORCE_REFRESH_KEY';
// Inspired by: https://raphael-leger.medium.com/react-webpack-chunkloaderror-loading-chunk-x-failed-ac385bd110e0
const lazyWithRetry = (key: string, componentImport: Parameters<typeof lazy>[0]) =>
lazy(async () => {
const forceRefreshKey = BASE_REFRESH_KEY + key
const pageHasAlreadyBeenForceRefreshed = JSON.parse(
window.localStorage.getItem(forceRefreshKey) || 'false',
);
const hardReload = () => {
const url = window.location.href;
window.location.href = url;
};
try {
const component = await componentImport();
window.localStorage.setItem(forceRefreshKey, 'false');
return component;
} catch (error) {
if (!pageHasAlreadyBeenForceRefreshed) {
window.localStorage.setItem(forceRefreshKey, 'true');
hardReload();
return {
default() {
return <>reloading</>;
},
};
}
throw error;
}
});
export default lazyWithRetry;