Skip to content

Instantly share code, notes, and snippets.

@itsjustcon
Last active December 16, 2015 00:39
Show Gist options
  • Save itsjustcon/5349332 to your computer and use it in GitHub Desktop.
Save itsjustcon/5349332 to your computer and use it in GitHub Desktop.
A simple JavaScript pre-processing script using Node.js that uglifies/minifies multiple js files into a single js file. Drastically reduces the number of GET requests by mixing all required js files into one. 1. Drop JScompiler.js and struct.json into a folder with all your js files 2. Modify struct.json to fit your file names, included files/im…
var UglifyJS = require('uglify-js');
fs = require('fs'),
path = require('path'),
struct = path.join(__dirname,'struct.json'),
files = {};
// Watch current folder & compile if file from files{} has changed
fs.watch(__dirname,function (evt,file) {
file = path.relative(__dirname,file);
if (!file) return;
if (file === 'struct.json') return updateFiles();
if (!files[file]) return;
var sources = [];
for (s in files[file]['src'])
sources[s] = path.join(__dirname,files[file]['src'][s]);
var result = UglifyJS.minify( sources ),
destination = path.join(__dirname,files[file]['dest']);
fs.writeFile(destination,result.code);
});
// Simply reads struct.json into files{}
updateFiles();
function updateFiles () {
fs.readFile(struct,function (err, data) {
if(err) return console.log(err);
files = JSON.parse(data);
});
}
{
"myFile.js" : {
"src" : [
"includedScript1.js",
"includedScript2.js",
"folder/include3.js",
"thisWillComeBeforeMyFile.js",
"myFile.js",
"thisWillComeAfterMyFile.js"
],
"dest" : "../www/myFile.js"
},
"myFile2.js" : {
"src" : [
"jquery/jquery.js",
"etc/json2.js",
"etc/modernizr.js",
"bootstrap/bootstrap.js",
"jquery/jquery.transit.js",
"jquery/jquery.modalMe.js",
"myFile2.js"
],
"dest" : "../www/myFolder/myFile2-condensed.js"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment