DEV Community

Discussion on: Clear Cache on build for React Apps.

Collapse
 
arturogallegos profile image
Arturo Gallegos

When your project requires to implement strict security policies in some cases it is necessary to disable hashes, for this reason we need another option to clear all caches.

however I agree that this method could be shorter, in my opinion only need attach in the serviceWorker.js a console.log with current date

Collapse
 
ammartinwala52 profile image
Ammar Tinwala

Hi Arturo

I'm extremely sorry for such a late reply. Can you help me out how I can make this code shorter ?

Thread Thread
 
arturogallegos profile image
Arturo Gallegos

Of course, as I commented only need attach a console log in your service worker, for example:

Create a file updateBuildTime.js

const fs = require('fs');

const sw_file = './src/forceUpdateCache.js';

const buildDate = `console.log(${new Date().getTime()})`

fs.writeFile(sw_file, buildDate, "utf8", (error) => {
  if(error){
    return console.warn(error);
  }
  return console.warn('All right')
});
Enter fullscreen mode Exit fullscreen mode

then update your package file with

"scripts": {
   ....
    "build": "node ./updateBuildTime.js && node scripts/build.js && cat src/forceUpdateCache.js >> build/service-worker.js",
    ....
  },
Enter fullscreen mode Exit fullscreen mode

With these lines you can add a console.log, I have used the current date to ensure a new value is different to the last version, but you can use another value

The reason of this is very simple, own service worker update all cache our app but need at least one change to download the new version of this file, the console.log with a date is perfect, it will be diferent in each build.

Thread Thread
 
ammartinwala52 profile image
Ammar Tinwala

Thanks Arturo, I will check this out.