On static files throughout the site I include the assembly number from TFS build as the querystring param for cachebusting typeof(NavigationHelper).Assembly.GetName().Version;
I want to be able to do something like this to update the static cache name in the service worker so that each time I deploy the site it will invalidate the service worker cache and fetch the latest files. I currently have...
const staticCacheName = "abc-cache-v1";
but i don't want to manually update that staticCacheName every time. i ideally want to end up with something like
const staticCacheName = "abc-cache-v" + DYNAMIC_VERSION_NUMBER;
The service worker doesn't have access to document or window so fetching the assembly build number from the page is out and the service worker is in a .js file so can't access any MVC Razor logic so I'm stumped. 🤔
Any thoughts on a work around? I've seen a solution using webpack but I dont want to implement webpack just for a versioning on one file. The rest of the js & assets are served up from a CDN so this would be overkill for just 2 js files in the root of the site.
I ended up adding a build event on the Visual Studio build and called a powershell script from it.
The Pre-build event command line code:
powershell.exe -ExecutionPolicy Unrestricted -File $(ProjectDir)ReplaceCacheText.ps1 -targetPath $(ProjectDir)\sw.js
And the Powershell script:
param([string]$targetPath);
$Replace = "serviceworker-cache-v{0}" -f (Get-Date -format s)
(Get-Content -Path $targetPath) -replace 'serviceworker-cache-v[^"]*',$Replace | Set-Content -Path $targetPath
Here we are searching for the start of the string and replacing the rest of the line until we hit the limiting character " in order to replace the contents within the "". Without [^"] it would greadily replace the entire rest of the string including the "; at the end of the line.
Big thanks to AdminOfThings for help with powershell regex Powershell script help needed - Find word beginning with something and replace it
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