Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

caching issue with web application developed using reactjs & webpack

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>
like image 733
OpenStack Avatar asked Apr 07 '16 15:04

OpenStack


2 Answers

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.

like image 170
Jack Avatar answered Sep 23 '22 22:09

Jack


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.

like image 45
Pranay Tripathi Avatar answered Sep 24 '22 22:09

Pranay Tripathi