MULTI-PLATFORM USE CASES and OPTIONAL STORAGE CLEARING (following Paras answer).
Since the script shell for npm is CMD.exe by default and since CMD.exe does not support command substitution.
By command substitution, I mean this syntax which takes the return value for a command and uses it as an argument for another
REACT_APP_CURRENT_GIT_SHA=`git rev-parse --short HEAD`
The workaround that worked for me was to change the script shell for npm to bash by running this in powershell
npm config set script-shell "C:\\Program Files\\git\\bin\\bash.exe"
Note that you need to have git installed
And then using cross-env so I can use a single syntax for both linux and windows platforms
My package.json script ended up looking like this
{
"start": "cross-env REACT_APP_CURRENT_GIT_SHA=$(git rev-parse --short HEAD) REACT_APP_CLEAR_STORAGE=${npm_config_clear_storage} react-scripts start",
"build": "cross-env REACT_APP_CURRENT_GIT_SHA=$(git rev-parse --short HEAD) REACT_APP_CLEAR_STORAGE=${npm_config_clear_storage} react-scripts build"
}
I added REACT_APP_CLEAR_STORAGE=${npm_config_clear_storage}
so I could manually specify when running the scripts if I wanted the localStorage to get cleared. (If you do not want this, do not add it)
Note that the extra argument works when the version (REACT_APP_CURRENT_GIT_SHA) changes only
My code now looks like this
const APP_VERSION = process.env.REACT_APP_CURRENT_GIT_SHA;
const CLEAR_STORAGE = !!process.env.REACT_APP_CLEAR_STORAGE;
if (localStorage.APP_VERSION != APP_VERSION) {
if (CLEAR_STORAGE) {
localStorage.clear();
}
localStorage.setItem("APP_VERSION", APP_VERSION);
}
And to run build and clear localStorage, I do npm run build --clear_storage
Meanwhile, to run build without clearing localStorage, I just do npm run build