Jan 04, 2013 in Bash, Closure compiler, Projects
Usually when the project is ready for production developer needs to minimize source files in order to reduce download time and save bandwidth. There are a number of perfect compressors which can significantly lower the file sizes.
The following bash script is a simple tool I use to get my project ready for the live. You run the script with the list of names of javascript files you want to include into resulting build script, and in the end you get all this files compiled and appended to the one resulting file.
Run next command in terminal:
$ ./compressJS.sh jquery-ui-1.8.16.custom.min.js chat-widget.js templ.min.js
#!/bin/bash
# Constants
SERVICE_URL=http://closure-compiler.appspot.com/compile
NEWFILE="c`date +"%d%m%y"`.js"
# Check if files to compile are provided
if [ $# -eq 0 ]
then
echo 'Nothing to compile. Specify input files as command arguments. E.g.'
echo './compressjs file1.js file2.js file3.js'
exit
fi
# Itearate through all files
for f in $*
do
if [ -r ${f} ]
then
code="${code} --data-urlencode js_code@${f}"
else
echo "File ${f} does not exist or is not readable. Skipped."
fi
done
# Send request
curl \
--url ${SERVICE_URL} \
--header 'Content-type: application/x-www-form-urlencoded' \
${code} \
--data output_format=json \
--data output_info=compiled_code \
--data output_info=statistics \
--data output_info=errors \
--data compilation_level=SIMPLE_OPTIMIZATIONS |
python -c '
import json, sys
data = json.load(sys.stdin)
if "errors" in data:
print "### COMPILATION FAILED WITH ERRORS"
for err in data["errors"]:
file = sys.argv[int(err["file"].replace("Input_", "")) + 1]
print "File: %s, %d:%d" % (file, err["lineno"], err["charno"])
print "Error: %s" % err["error"]
print "Line: %s" % err["line"]
print "\nBuild failed.\n"
else:
print "### COMPILATION COMPLETED"
print "Original size: %db, gziped: %db" % (data["statistics"]["originalSize"], data["statistics"]["originalGzipSize"])
print "Compressed size: %db, gziped: %db" % (data["statistics"]["compressedSize"], data["statistics"]["compressedGzipSize"])
print "Compression rate: %.2f" % (float(data["statistics"]["compressedSize"]) / int(data["statistics"]["originalSize"]))
filename = "'${NEWFILE}'"
f = open(filename, "w")
f.write(data["compiledCode"])
print "\nBuild file %s created.\n" % filename
' $@
comments powered by Disqus