使用 CRA React 清除缓存

Cache busting with CRA React

当我更新我的网站时,运行 npm 运行 构建新文件并将其上传到服务器我仍在寻找我网站的旧版本。

在没有 React 的情况下,我可以看到带有缓存破坏功能的网站的新版本。我这样做:

上一个文件

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

新文件

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

我怎样才能做这样的事情或通过 create react app 实现缓存破坏?

create react app 的 GitHub 中有很多关于此的主题,但没有人有 proper/simple 答案。

编辑:create-react-appv2 现在默认禁用 service worker

此答案仅适用于 CRA v1

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

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

registerServiceWorker();

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

// 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.

如果要删除网络工作者,不要只删除该行。导入取消注册并在您的文件中调用它而不是注册。

import { unregister } from './registerServiceWorker';

然后调用

unregister()

P.S。注销后,至少需要刷新一次才能生效

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

我发现问题似乎出在浏览器端,它用过时的 js 包

缓存了我的旧 index.html

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

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

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

"headers": { 
    "/**": { 
        "Cache-Control": "no-store, no-cache" 
    } 
}

我觉得这样还是可以留住那个可怜的service worker,而且最新的内容会在N+1加载时显示(二次刷新)

希望这对您有所帮助...

关于 Service Worker,他们似乎从选择退出更改为选择加入。这是更改自述文件的提交,它有类似于 Kerry G 的回答的示例:

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

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

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

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

在你的index.html中:

<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.

正如此处之前的一些答案所提到的,服务工作人员和(缺乏)缓存 headers 在看到您的 React 应用程序的旧版本时可能会合谋反对您。

React 文档在谈到 caching 时声明如下:

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 默认为 opt-out service worker 注册,而较新版本为 opt-in。如果您从 create-react-app 的旧版本开始并且想切换到新的行为,您可以在 official docs. It's quite a straightforward process to match you configuration to the latest template 中阅读更多相关信息。

相关问题: