html - 如何在 create-react-app 中为 index.html 指定 Cache-Control header

标签 html reactjs caching create-react-app

我正在尝试遵循 create-react-app.dev 的指南 Production Build documentation :

To deliver the best performance to your users, it's best practice to specify a Cache-Control header for index.html, as well as the files within build/static. This header allows you to control the length of time that the browser as well as CDNs will cache your static assets. If you aren't familiar with what Cache-Control does, see this article for a great introduction.


Using Cache-Control: max-age=31536000 for your build/static assets, and Cache-Control: no-cache for everything else is a safe and effective starting point that ensures your user's browser will always check for an updated index.html file, and will cache all of the build/static files for one year. Note that you can use the one year expiration on build/static safely because the file contents hash is embedded into the filename.


这样做的正确方法是在 index.html 中使用 HTML header - 例如:
<meta http-equiv="Cache-Control" content="max-age: 31536000, no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
(来源:this stack overflow responsethis YouTube tutorial)
如果是这样,我该如何遵循文档的建议,即我应该为您的构建/静态 Assets 设置“max-age=31536000,并为其他所有内容设置 Cache-Control: no-cache”?我不知道如何为不同的 Assets 设置不同的控件。

最佳答案

正如埃文斯提到的,这个头应该从服务器端设置。您实际设置 header 的方式因后端编程语言/服务器而异。
这里有一些例子:

  • Node.js res.setHeader('Cache-Control', 'no-cache');
  • Nginx add_header Cache-Control no-cache;
  • 关于html - 如何在 create-react-app 中为 index.html 指定 Cache-Control header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65528622/

    相关文章:

    reactjs - 如何将 React webapp 集成到带有 jar 包装的 Spring Boot 应用程序中

    Java缓存机制

    reactjs - react 原生天才聊天中的输入被键盘覆盖

    reactjs - getDerivedStateFromProps 未被调用

    html - Bootstrap 4 Multiple Item Carousel(点击循环所有新元素)

    html - 如果屏幕像素密度发生变化,css像素单元物理尺寸是否会发生变化?

    c - ccache "called for link"是什么意思

    javascript - ServiceWorker 不更新缓存

    html - Angular 5 如何等待 styles.css 加载

    html - 放大浏览器时站点显示问题