Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple JS and CSS minification script
#!/bin/bash
#
# Minify every JS and CSS file in the given directories, except for anything with "min" in the name.
# Creates new files with the names *.min.js and *.min.css. Deletes the originals. Modified all the html files
# to say ".min.js" and ".min.css" instead of ".js" and ".css".
# Also has an optional debug mode that removes strict mode without minifying.
#
# usage: minify_everything.sh my/yuicompressor.jar my/js/folder my/css/folder debug_mode[0,1] [htmlFiles ...]
#
jarfile=$1
jsfolder=$2
cssfolder=$3
debugmode=$4
htmlfiles="${@:5}"
if [ -z $jarfile ]; then
echo "jarfile not found: $jarfile";
echo "usage: minify_everything.sh my/yuicompressor.jar my/js/folder my/css/folder debug_mode[0,1] [htmlFiles ...]"
exit 1;
fi
cssfiles=`find $cssfolder -name *\.css | grep -v min | tr '\n' ' '`
jsfiles=`find $jsfolder -name *\.js | grep -v min | tr '\n' ' '`
jscount=`echo $jsfiles | wc -w | tr -d ' '`
csscount=`echo $cssfiles | wc -w | tr -d ' '`
# rename everything in the html files
if [ $jscount != 0 ]; then
for jsfile in $jsfiles; do
basefile=`basename $jsfile`
minfile=`echo $basefile | sed 's/\.js/.min.js/g'`
sed -i "s/$basefile/$minfile/g" $htmlfiles
done
fi
if [ $csscount != 0 ]; then
for cssfile in $cssfiles; do
basefile=`basename $cssfile`
minfile=`echo $basefile | sed 's/\.css/.min.css/g'`
sed -i "s/$basefile/$minfile/g" $htmlfiles
done
fi
if [ $debugmode == 1 ]; then
echo "running in debug mode..."
echo "renaming $jscount js files..."
if [ $jscount != 0 ]; then
for jsfile in $jsfiles; do
# remove strict mode, or else it screws up WEINRE
sed -i '/use\ strict/d' $jsfile
mv $jsfile `echo $jsfile | sed 's/\.js/.min.js/g'`;
done;
fi
echo "renaming $csscount css files..."
if [ $csscount != 0 ]; then
for cssfile in $cssfiles; do
mv $cssfile `echo $cssfile | sed 's/\.css/.min.css/g'`;
done;
fi
exit 0;
fi
echo -e "\nusing jar $jarfile..."
echo "minifying $jscount files in js folder $jsfolder..."
if [ $jscount == 0 ]; then
echo "no javascript files found";
elif [ $jscount == 1 ]; then
java -jar $jarfile --type js -o `echo $jsfiles | sed 's/js$/min.js/g'` $jsfiles
else
java -jar $jarfile --type js -o '.js$:.min.js' $jsfiles
fi;
echo "minifying $csscount files in css folder $cssfolder..."
if [ $csscount == 0 ]; then
echo "no css files found";
elif [ $csscount == 1 ]; then
java -jar $jarfile --type css -o `echo $cssfiles | sed 's/css$/min.css/g'` $cssfiles
else
java -jar $jarfile --type css -o '.css$:.min.css' $cssfiles
fi;
echo
rm -f $jsfiles $cssfiles
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment