我正在部署一个使用CRA(Create-React-App)生成的项目,并且所有的babel和webpack配置都保持不变。
此外,我正在使用亚马逊网络服务S3的静态存储桶托管功能部署我的React应用程序。
问题是,由于没有包含服务器,所以每次部署新文件时,都会创建具有随机哈希的新块。
当客户端使用旧的散列在网站中,并且部署了新的散列时,客户端收到块加载错误。
要演示这一点,请使用yarn build构建项目,然后转到/build文件夹查看由webpack生成的块。然后使用serve,我可以演示我的部署在我的本地机器上的行为。
执行yarn serve后,转到提供构建文件的相应本地主机。
然后,在/build/static/js文件夹中,根据需要重命名每个块文件的散列。
不使用浏览器,重新启动yarn serve,它将提供重命名的块文件。
然后返回到浏览器,您很可能会得到两个错误:
Uncaught SyntaxError: Unexpected token '<'
Loading Chunk n failed.(missing: ~~)我认为可以解决这个问题的方法是在ChunkLoadError发生时硬重新加载网页。遗憾的是,window.reload(boolean)函数已经被弃用,只使用window.location.reload()并不能解决这个问题。
+) PS。我在一些代码中使用React.Lazy()实现了代码拆分。
发布于 2021-09-29 18:22:13
您提出的解决方案必须有效:
你所要做的就是将这两个元标签添加到你的index.html中:
<meta http-equiv="Pragma" content="no-cache"/>
<meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate"/>
这将防止浏览器在刷新页面时使用缓存
其次,使用react的ErrorBoundary组件来放置刷新逻辑
例如:
import React from "react";
const PageHasBeenForceRefreshed = "page-has-been-force-refreshed";
const retryPageLoading = () => {
const pageHasAlreadyBeenForceRefreshed = JSON.parse(
window.localStorage.getItem(PageHasBeenForceRefreshed) || "false"
) as boolean;
if (!pageHasAlreadyBeenForceRefreshed) {
window.localStorage.setItem(PageHasBeenForceRefreshed, "true");
return window.location.reload();
} else {
window.localStorage.setItem(PageHasBeenForceRefreshed, "false");
}
};
interface ErrorBoundaryProps {
children: React.ReactNode;
}
export class ErrorBoundary extends React.Component<ErrorBoundaryProps, { hasError: boolean }> {
constructor(props: Readonly<ErrorBoundaryProps>) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error: unknown, info: unknown) {
retryPageLoading();
this.setState({ hasError: true });
console.log(error, info);
}
render() {
if (this.state.hasError) {
return <>Your error component</>;
}
return this.props.children;
}
}
当index.html中缺少一个块时,错误边界将捕获错误并运行函数"retryPageLoading()“。函数"retryPageLoading()“使用本地存储来避免无限循环。当发生错误并且页面没有刷新yes时,刷新由"window.location.reload()“完成
最后,将您的react应用程序包装在ErrorBoundary中,以便在缺少块错误时捕获它
import * as React from "react";
import { ErrorBoundary } from "./components/ErrorBoundary/ErrorBoundary";
const App: React.FunctionComponent = () => {
return <ErrorBoundary>Your app</ErrorBoundary>;
};
告诉我它是不是能用。祝好运
https://stackoverflow.com/questions/68663106
复制相似问题