Skip to content

Instantly share code, notes, and snippets.

@jiaming0708
Created February 25, 2017 10:57
Show Gist options
  • Save jiaming0708/ad926b08234864967c36a72950eb86d1 to your computer and use it in GitHub Desktop.
Save jiaming0708/ad926b08234864967c36a72950eb86d1 to your computer and use it in GitHub Desktop.
cordova hooks
#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var jshint = require('jshint').JSHINT;
var async = require('async');
var recursiveFolderSearch = true;
var foldersToProcess = [
'js'
];
foldersToProcess.forEach(function (folder) {
processFiles("www/" + folder);
});
function processFiles(dir, callback) {
var errorCount = 0;
fs.readdir(dir, function (err, list) {
if (err) {
console.error('Directory Error: ' + err);
return;
}
async.eachSeries(list, function (file, innercallback) {
file = dir + '/' + file;
fs.stat(file, function (err, stat) {
if (!stat.isDirectory()) {
if (path.extname(file) === ".js") {
lintFile(file, function (hasError) {
if (hasError) {
errorCount++;
}
innercallback();
});
} else {
innercallback();
}
} else {
if (stat.isDirectory() && recursiveFolderSearch) {
processFiles(file, callback);
} else {
innercallback();
}
innercallback();
}
});
}, function (error) {
if (errorCount > 0) {
console.error('Get ' + errorCount + ' error(s) by JSHint.');
process.exit(1);
}
});
});
}
function lintFile(file, callback) {
console.log("Linting " + file);
fs.readFile(file, function (err, data) {
if (err) {
console.log('Error: ' + err);
return;
}
if (jshint(data.toString())) {
console.log('File ' + file + ' has no errors.');
console.log('-----------------------------------------');
callback(false);
} else {
console.log('Errors in file ' + file);
var out = jshint.data(),
errors = out.errors;
for (var j = 0; j < errors.length; j++) {
console.log(errors[j].line + ':' + errors[j].character + ' -> ' + errors[j].reason + ' -> ' +
errors[j].evidence);
}
console.log('-----------------------------------------');
callback(true);
}
});
}
#!/usr/bin/env node
// Parses the index.html file search for js and css files.
// v1.0
// all the files will be concatenated in 2 files.
// Note: It does not touch cordova.js.
// appConcatFolder: folder for the js bundle.
// appConcatFile: name of the js file bundle.
// cssConcatFolder = folder of the css bundle;
// cssConcatFile = name of the css file bundle;
var fs = require('fs');
var path = require('path');
var htmlparser = require("htmlparser2");
var Concat = require('concat-with-sourcemaps');
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 = (cliCommand.indexOf('--release') > -1) || (cliCommand.indexOf('--runrelease') > -1);
// isRelease = true;
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;
}
console.log('************************************************************************************');
console.log('... Parsing index.html for references (js & css) and concatenation ...');
console.log('************************************************************************************');
var appConcatFolder = 'js';
var appConcatFile = 'app.min.js';
var cssConcatFolder = 'css';
var cssConcatFile = 'app.min.css';
// Creating folder if it does not exist.
if (!fs.existsSync(path.join(platformPath, appConcatFolder))) {
fs.mkdirSync(path.join(platformPath, appConcatFolder));
}
if (!fs.existsSync(path.join(platformPath, cssConcatFolder))) {
fs.mkdirSync(path.join(platformPath, cssConcatFolder));
}
// Processing index.html to file js file and css files.
var elements = processIndexHtml(path.join(platformPath, "index.html"));
// Removes all the scripts and css files referenced in the index.html
// Removes other folders.
if (elements) {
if (elements.scripts.length > 0) {
elements.scripts.forEach(function (file) {
console.log('Removing referenced file: ' + path.join(platformPath, file));
fs.unlink(path.join(platformPath, file),
function (err) {
if (err) {
console.log(err);
throw err;
}
});
});
}
if (elements.css.length > 0) {
elements.css.forEach(function (file) {
console.log('Removing referenced file: ' + path.join(platformPath, file));
fs.unlink(path.join(platformPath, file),
function (err) {
if (err) {
console.log(err);
throw err;
}
});
});
}
}
// Read the index.html file and extracts all the references to scripts and css.
// compacts js in one file
// compacts css in one file.
function processIndexHtml(file) {
var html = readIndexHtml(file);
if (!html) {
return null;
}
var elements = parseIndexHtml(html);
if (!elements) {
return null;
}
if (elements.scripts.length > 0) {
var concatJs = new Concat(false, appConcatFile, '\n');
elements.scripts.forEach(function (file) {
console.log('Processing file for concatenation : ' + path.join(platformPath, file));
var fileContent = String(fs.readFileSync(path.join(platformPath, file)));
concatJs.add(file, fileContent);
});
fs.writeFileSync(path.join(platformPath, appConcatFolder + '/' + appConcatFile), concatJs.content);
} else {
console.log('No js scripts to process.');
}
if (elements.css.length > 0) {
var concatCss = new Concat(false, cssConcatFile, '\n');
elements.css.forEach(function (file) {
console.log('Processing file for concatenation : ' + path.join(platformPath, file));
var fileContent = String(fs.readFileSync(path.join(platformPath, file)));
concatCss.add(file, fileContent);
});
fs.writeFileSync(path.join(platformPath, cssConcatFolder + '/' + cssConcatFile), concatCss.content);
} else {
console.log('No css scripts to process.');
}
return elements;
}
// Parse index.html file to get all the references to js scripts and css files.
function parseIndexHtml(html) {
var scripts = [];
var css = [];
var parser = new htmlparser.Parser({
onopentag: function (name, attribs) {
console.log(JSON.stringify(attribs));
if (name === "script" && attribs.src.startsWith('js/')) {
scripts.push(attribs.src);
} else if (name === "link" && attribs.rel === "stylesheet") {
css.push(attribs.href);
}
},
ontext: function (text) {},
onclosetag: function (tagname) {}
}, {
decodeEntities: true
});
parser.write(html);
parser.end();
return {
scripts: scripts,
css: css
};
}
function readIndexHtml(file) {
// var opts = {};
try {
var html = String(fs.readFileSync(file));
return html;
} catch (err) {
console.log('readIndexHtml => Error', err);
return "";
}
}
#!/usr/bin/env node
// useref index.html
// v1.0
// searches the node-useref tags in your index.html to replace it width
// the bundle.
// https://www.npmjs.com/package/node-useref
var fs = require('fs');
var path = require('path');
var useref = require('node-useref');
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 = (cliCommand.indexOf('--release') > -1) || (cliCommand.indexOf('--runrelease') > -1);
// isRelease = true;
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;
}
console.log('************************************************************************************');
console.log('... useref index.html ...');
console.log('************************************************************************************');
userefIndexHtml(path.join(platformPath, "index.html"));
function userefIndexHtml(file) {
var opts = {};
try {
var res = fs.readFileSync(file, {
encoding: 'utf-8'
});
var output = useref(res, opts);
var html = output[0];
fs.writeFileSync(file, html);
} catch (err) {
console.log('userefIndexHtml: Error', err);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment