-
-
Save omelsoft/5ceb9fb98b20c7928937a55603ce49c8 to your computer and use it in GitHub Desktop.
ionic cache busting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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()); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# run this command in your terminal to give npm permission to run the cache busting script | |
chmod 755 ./cache-busting.js |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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