关于reactjs:使用CRA React进行缓存清除

Cache busting with CRA React

当我更新站点时,运行npm run build并将新文件上传到服务器,但我仍在查找站点的旧版本。

没有React,我可以看到带有缓存清除功能的网站的新版本。我这样做:

上一个文件

1
<link rel="stylesheet" href="/css/styles.css">

新文件

1
<link rel="stylesheet" href="/css/styles.css?abcde">

我该怎么做或通过create react app实现缓存清除?

在GitHub上有很多关于此问题的create react app线程,但是没有人给出正确/简单的答案。


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

此答案仅适用于CRA v1

这可能是由于您的网络工作者。

如果您查看index.js文件,您会看到

1
registerServiceWorker();

从来没有想过它做了什么?如果我们查看从中导入的文件,我们可以看到

1
2
3
4
5
6
7
8
9
// 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.

如果要删除网络工作者,请不要仅删除该行。导入注销并在文件而不是注册中调用它。

1
import { unregister } from './registerServiceWorker';

,然后致电

1
unregister()

P.S。取消注册后,至少需要刷新一次才能使其生效


当我使用create-react-app并部署到heroku时遇到相同的问题。它一直显示我的应用程序的旧版本??。

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

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

1
"Cache-Control":"no-store, no-cache"

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

1
2
3
4
5
"headers": {
   "/**": {
       "Cache-Control":"no-store, no-cache"
    }
}

我认为通过这种方式您仍然可以保留可怜的服务人员??,并且最新内容将显示在N 1负载(第二次刷新)上

希望这对您有帮助...


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

React文档在缓存时声明以下内容:

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.

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

相关问题:

  • 如何避免为create-react-app缓存
  • ReactJS:如何防止浏览器缓存静态文件?
  • 如何清除reactjs中的浏览器缓存


如果您的问题是在index.html中静态引用的资源,例如.css文件或其他.js文件(例如,配置文件),则可以声明一个React环境变量,为其分配一个唯一值并在其中引用它您的index.html文件。

在您的构建脚本(bash)中:

1
REACT_APP_CACHE_BUST={e.g. build number from a CI tool} npm run build

在您的index.html中:

1
<link rel="stylesheet" href="%PUBLIC_URL%/index.css?cachebust=%REACT_APP_CACHE_BUST%" />

变量名称必须以REACT_APP_开头。有关React中环境变量的更多信息:https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables。


对于服务人员,他们似乎从选择退出更改为选择加入。这是更改自述文件的提交,它的示例类似于Kerry G的答案:

https://github.com/facebook/create-react-app/commit/1b2813144b3b0e731d8f404a8169e6fa5916dde4#diff-4e6ec56f74ee42069aac401a4fe448ad