Skip to content

Instantly share code, notes, and snippets.

@marcocarnazzo
Created April 16, 2015 10:36
Show Gist options
  • Save marcocarnazzo/fab95685da10bb94564e to your computer and use it in GitHub Desktop.
Save marcocarnazzo/fab95685da10bb94564e to your computer and use it in GitHub Desktop.
Ionic/Cordova hook to remove junk from release build
#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var rootDir = process.argv[2];
var platformPath = path.join(rootDir, 'platforms');
var platform = process.env.CORDOVA_PLATFORMS;
var cliCommand = process.env.CORDOVA_CMDLINE;
// hook configuration
//var isRelease = true; // by default this hook is always enabled, see the line below on how to execute it only for release
var isRelease = (cliCommand.indexOf('--release') > -1);
var recursiveFolderSearch = true; // set this to false to manually indicate the folders to process
var foldersToProcess = [ // add other www folders in here if needed (ex. js/controllers)
'lib'
];
var junkPatterns = [ // add filename regex patterns to identify junk files
/^(?!.*www\/lib\/.*\.(js|css|map)$)/, // All library files except .js and .css
/\/www\/lib\/.*\/src\/.*/, // All library original sources
/\/www\/lib\/.*\/examples\/.*/, // All library examples
/\/www\/lib\/.*\/tutorials\/.*/ // All library tutorials
];
if (!isRelease) {
return;
}
switch (platform) {
case 'android':
platformPath = path.join(platformPath, platform, 'assets', 'www');
break;
case 'ios':
platformPath = path.join(platformPath, platform, 'www');
break;
default:
console.log('this hook only supports android and ios currently');
return;
}
foldersToProcess.forEach(function(folder) {
processFiles(path.join(platformPath, folder));
});
function processFiles(dir) {
fs.readdir(dir, function (err, list) {
if (err) {
console.log('processFiles err: ' + err);
return;
}
list.forEach(function(file) {
file = path.join(dir, file);
fs.stat(file, function(err, stat) {
if (stat.isDirectory()) {
if (recursiveFolderSearch ) {
processFiles(file);
}
} else {
cleanFile(file);
}
});
});
});
}
function cleanFile(file) {
var isJunk = false;
var i;
var len = junkPatterns.length;
for (i = 0; i < len; i++) {
if (junkPatterns[i].test(file)) {
isJunk = true;
break;
}
}
if (isJunk) {
fs.unlink(file, function (error) {
console.log("Removed file " + file);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment