Skip to content

Instantly share code, notes, and snippets.

@omelsoft
Forked from haydenbr/cache-busting.js
Last active February 16, 2020 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omelsoft/5ceb9fb98b20c7928937a55603ce49c8 to your computer and use it in GitHub Desktop.
Save omelsoft/5ceb9fb98b20c7928937a55603ce49c8 to your computer and use it in GitHub Desktop.
ionic cache busting
#!/usr/bin/env node
var fs = require('fs'),
path = require('path'),
cheerio = require('cheerio'),
revHash = require('rev-hash');
/**
*
* @param string fileName
* @returns string
*/
function hashFile(file) {
// Get file name
var fileName = file.replace(/\.[^/.]+$/, "");
// Get file extension
var re = /(?:\.([^.]+))?$/;
var fileExtension = re.exec(file)[1];
var filePath = path.join(buildDir, file);
var fileHash = revHash(fs.readFileSync(filePath));
var fileNewName = `${fileName}.${fileHash}.${fileExtension}`;
var fileNewPath = path.join(buildDir, fileNewName);
var fileNewRelativePath = path.join('build', fileNewName);
//Rename file
console.log(`${fileName}.${fileExtension} >> ${fileName}.${fileHash}.${fileExtension}`);
fs.renameSync(filePath, fileNewPath);
return fileNewRelativePath;
}
var rootDir = path.resolve(__dirname, '././');
var wwwRootDir = path.resolve(rootDir, 'www');
var buildDir = path.join(wwwRootDir, 'build');
var indexPath = path.join(wwwRootDir, 'index.html');
$ = cheerio.load(fs.readFileSync(indexPath, 'utf-8'));
$('head link[href="build/main.css"]').attr('href', hashFile('main.css'));
$('body script[src="build/main.js"]').attr('src', hashFile('main.js'));
$('body script[src="build/polyfills.js"]').attr('src', hashFile('polyfills.js'));
$('body script[src="build/vendor.js"]').attr('src', hashFile('vendor.js'));
fs.writeFileSync(indexPath, $.html());
# run this command in your terminal to give npm permission to run the cache busting script
chmod 755 ./cache-busting.js
{
"author": "Unboxed Technology",
"homepage": "https://www.unboxedtechnology.com/",
"scripts": {
"build": "ionic cordova build browser --release --prod --no-interactive",
"postbuild": "node ./cache-busting.js"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment