我有一个 React 应用程序,每次重新部署时,用户都会告诉我他们看不到更改。我要求他们进行硬重置并清除缓存。我想在推送新版本时破坏浏览器缓存,以便用户看到更改。
我最初使用react-create-app来创建应用程序。
我读到here你应该在你的 webpack 插件中使用 hash: true 。我这样做了,现在我看到捆绑的 react 应用程序现在有一个查询字符串,但现在我收到错误:
Refused to execute script from 'https://example.com/static/js/main.9b80cc8a.js?76de7bb1d01e56c5fcb0' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled
该错误已被覆盖 here与 Node 。我正在使用express.static
我从这里更改了网络包:
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}),
对此:
new HtmlWebpackPlugin({
hash: true,
inject: true,
template: paths.appHtml,
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}),
我的 Node 代码如下所示,我认为是正确的:
app.use(express.static(path.join(__dirname, 'public')));
公共(public)目录包含生产构建的应用程序。
如何在应用更新时防止此错误并清除浏览器缓存?
最佳答案
我更愿意发表评论,但我没有足够的声誉:p。
我们对不同类型的应用程序有类似的设置。每次我们运行构建时,新包的哈希值都会添加到 HTML 中脚本标记的源中。这是我们的HtmlWebpackPlugin
配置。
new HtmlWebpackPlugin({
inject: false,
hash: true,
template: '../runner.html',
filename: 'index.html',
}),
我们的设置之间的主要区别是 inject
在我的中设置为 false 。我们不想注入(inject)整个js
构建到 html 中。
这是 ../runner.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Spec Runner v3.1.0</title>
<!-- include spec files here... -->
<script src="<%= htmlWebpackPlugin.files.chunks.spec.entry %>"></script>
</head>
<body>
</body>
</html>
通知<%= htmlWebpackPlugin.files.chunks.ENTER-THE-CHUNK-NAME.entry %>
。这基本上告诉 webpack 将哈希值注入(inject)到页面中。这允许我们将更新直接包含到 html 页面中。当然,您仍然需要担心 html 页面的缓存时间。
此外,如果您决定这样做,您将需要另一个插件来缩小您的代码。我推荐uglifyjs 。文档可以帮助您指明正确的方向。
关于node.js - 使用 React 和 Node 破坏浏览器缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58633271/