I am working on a web application developed using reactjs and webpack. After every deployment, we have to ask users to clear the browser cache and restart their browsers. I think the javascript bundle file and css file both are getting cached on user browser.
How can we force browser not to cache these files or make it download the latest files from the server.
<html>
<head>
<meta charset="utf-8">
<title>My App</title>
<link rel="stylesheet" href="styles.css" media="screen" charset="utf-8">
</head>
<body>
<div id="app"></div>
<script src="bundle.js"></script>
</body>
</html>
You can use html-webpack-plugin
plugins: [
new HtmlWebpackPlugin({
hash: true
})
]
hash: true | false if true then append a unique webpack compilation hash to all included scripts and css files. This is useful for cache busting.
you should use html-webpack-plugin with an template html and put hash configuration in output. So your webpack config will look something like this:
output: {
filename: "[name].[hash].js",
path: <path to your bundle folder>
}
new HTMLWebpackPlugin({
hash: true,
template: paths.resolveFromRoot("src/index.html") //where you want the sample template to be
})
And your index.html will be something like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="expires" content="0">
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Title</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
The HTML webpack plugin will automatically insert the revised script in the index.html created in your bundle folder. Hope this helps. For caching fix you can refer to https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching where versioning and server response header configurations is mentioned for effective caching solutions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With