缓存破坏与创建反应应用程序

Alf*_*x92 36 caching reactjs react-redux create-react-app

当我更新我的网站时,运行npm run build并将新文件上传到服务器我仍在查看我的网站的旧版本.我的项目的回购是 https://github.com/Alfrex92/serverlessapps

没有React,我可以看到我的网站的新版本缓存破坏.我这样做:

上一个文件

<link rel="stylesheet" href="/css/styles.css">
Run Code Online (Sandbox Code Playgroud)

新文件

<link rel="stylesheet" href="/css/styles.css?abcde">
Run Code Online (Sandbox Code Playgroud)

我怎么能做这样的事情或用create react app实现缓存清除?

在创建的github中有许多线程对此做出反应,但没有人有正确/简单的答案.

Ker*_*eon 36

这可能是因为你的网络工作者.

如果你查看你的index.js文件,你可以看到

registerServiceWorker();
Run Code Online (Sandbox Code Playgroud)

从来不想知道它做了什么?如果我们看看它导入的文件,我们可以看到

// In production, we register a service worker to serve assets from local cache.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.

// To learn more about the benefits of this model, read {URL}
// This link also includes instructions on opting out of this behavior.
Run Code Online (Sandbox Code Playgroud)

如果要删除Web工作者,请不要删除该行.导入取消注册并在您的文件而不是寄存器中调用它.

import { unregister } from './registerServiceWorker';
Run Code Online (Sandbox Code Playgroud)

并告诉电话

unregister()
Run Code Online (Sandbox Code Playgroud)

PS取消注册时,至少需要一次刷新才能使其正常工作

编辑:create-react-app v2现在默认禁用服务工作者

  • @AhmadMaleki是的,如果您的项目未部署,这是一个很好的解决方案,但是如果您的网站已经在线并且有人让服务工作者工作; 只需删除这些行就不会取消注册. (2认同)

Rya*_*Chu 8

我使用create-react-app(并部署到heroku)时遇到了同样的问题.它一直显示我的应用程序的旧版本.

我发现问题似乎是在浏览器端,它用我index.html过时的js包缓存我的旧

您可能希望将以下内容添加到服务器端响应标头中

"Cache-Control": "no-store, no-cache"
Run Code Online (Sandbox Code Playgroud)

或者如果您还使用heroku create-react-app-buildpack,请更新该static.json文件

"headers": { 
    "/**": { 
        "Cache-Control": "no-store, no-cache" 
    } 
}
Run Code Online (Sandbox Code Playgroud)

我认为通过这种方式你仍然可以保留那个糟糕的服务工作者,最新的内容将显示在N + 1负载上(第二次刷新)

希望这可以帮助...

  • 你真的想要不缓存一切吗?这只是html文件的罪魁祸首吗? (16认同)

bsz*_*zom 6

正如此处先前的一些答案所提到的那样,当看到React应用程序的旧版本时,服务工作者和(缺乏)缓存头都可能对您不利。

当涉及到缓存时,React文档指出以下内容:

使用Cache-Control: max-age=31536000你的build/static 资产,以及Cache-Control: no-cache其他一切是确保你的用户的浏览器会经常检查更新的安全和有效抓手index.html文件,将缓存所有的build/static文件为一年。请注意,build/static由于文件内容哈希值已嵌入文件名中,因此可以安全地使用一年有效期。

如@squarism所述,较早版本的create-react-app默认选择退出服务工作者注册,而较新版本则选择加入。您可以在官方文档中了解有关此内容的更多信息。如果您从较早版本的create-react-app开始并且想要切换到新的行为,那么将配置与最新模板进行匹配的过程非常简单。

相关问题:

  • 感谢您在这里如此彻底,这是我的场景的最佳答案。如果其他人试图确保 Cloudfront 始终提供来自 S3 的最新应用程序,答案似乎是在网站的 `index.html` 对象上配置 `Cache-Control: max-age=0`桶。 (4认同)
  • @bszom 如何为 build/static 与 index.html 设置 Cache-Control: no-cache。元标记上有这个属性吗? (2认同)