Created
October 5, 2017 17:51
-
-
Save haydenbr/7df417a8678efc404c820c61b6ffdd24 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'); | |
var rootDir = path.resolve(__dirname, '../'); | |
var wwwRootDir = path.resolve(rootDir, 'platforms', 'browser', 'www'); | |
var buildDir = path.join(wwwRootDir, 'build'); | |
var indexPath = path.join(wwwRootDir, 'index.html'); | |
var cssPath = path.join(buildDir, 'main.css'); | |
var cssFileHash = revHash(fs.readFileSync(cssPath)); | |
var cssNewFileName = `main.${cssFileHash}.css`; | |
var cssNewPath = path.join(buildDir, cssNewFileName); | |
var cssNewRelativePath = path.join('build', cssNewFileName); | |
var jsPath = path.join(buildDir, 'main.js'); | |
var jsFileHash = revHash(fs.readFileSync(jsPath)); | |
var jsNewFileName = `main.${jsFileHash}.js`; | |
var jsNewPath = path.join(buildDir, jsNewFileName); | |
var jsNewRelativePath = path.join('build', jsNewFileName); | |
// rename main.css to main.[hash].css | |
fs.renameSync(cssPath, cssNewPath); | |
// rename main.js to main.[hash].js | |
fs.renameSync(jsPath, jsNewPath); | |
// update index.html to load main.[hash].css | |
$ = cheerio.load(fs.readFileSync(indexPath, 'utf-8')); | |
$('head link[href="build/main.css"]').attr('href', cssNewRelativePath); | |
$('body script[src="build/main.js"]').attr('src', jsNewRelativePath); | |
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": "./cache-busting.js" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In your package.json file, add
"postbuild": "node ./cache-busting.js"
after your build scripts like: