node.js - 使用 React 和 Node 破坏浏览器缓存
问题描述
我有一个 React 应用程序,每次我重新部署用户时都告诉我他们看不到更改。我要求他们进行硬重置并清除缓存。我想在推送新版本时破坏浏览器缓存,以便用户看到更改。
我最初使用 react-create-app 来创建应用程序。
我在这里读到你应该在你的 webpack 插件中使用 hash: true 。我这样做了,现在我看到捆绑的反应应用程序现在有一个查询字符串,但现在我收到错误:
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
该错误在此处使用 Node.js 进行了介绍。我正在使用 express.static
我从这里更改了 web pack:
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,
},
}),
我的节点代码如下所示,我认为这是正确的:
app.use(express.static(path.join(__dirname, 'public')));
公共目录包含生产构建的应用程序。
更新应用程序时如何防止此错误并清除浏览器缓存?
解决方案
我宁愿发表评论,但我没有足够的声誉:p。
对于不同类型的应用程序,我们有类似的设置。每次我们运行构建时,新包的哈希都会添加到 HTML 中脚本标记的源中。这是我们的HtmlWebpackPlugin
配置。
new HtmlWebpackPlugin({
inject: false,
hash: true,
template: '../runner.html',
filename: 'index.html',
}),
我们的设置之间的主要区别是在我的设置中inject
设置为 false。我们不想将整个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 将散列注入页面。这允许我们将更新直接包含到 html 页面中。当然,您仍然需要担心 html 页面的缓存时间。
此外,如果您决定这样做,您将需要另一个插件来缩小您的代码。我推荐uglifyjs。文档可以帮助您指明正确的方向。
推荐阅读
- javascript - 渲染 BehaviourSubject:可以在模板中使用 getValue() 吗?
- ios - UICollectionView 与 SwiftUI + 拖放重新排序可能吗?
- if-statement - onEdit 只运行脚本的一半
- amazon-web-services - 自动将 DynamoDB 表导出到 S3
- python - 更改系列中的值
- excel - ActiveX 组件无法创建对象 - 429
- java - RecyclerView 只显示一个值
- android - java.lang.NoClassDefFoundError:在 Firebase 测试实验室上运行记录的 Robo 测试时无法解决:Landroid/support/v7/widget/RecyclerView
- xml - 我如何将字符串放入 XmlDocument 中的 XmlElement
- cloudfoundry-uaa - 如何将 UAA 日志级别从 DEBUG 更改为 INFO?