tero.co.uk

Shell Command to Minmise Javascript and CSS

The following shell command can minimise (aka minify) Javascript and CSS files. Please try your CSS and Javascript after minimising as it's not a perfect script. Problems are shown below.

How it works
It removes comments from CSS and Javascript files using sed. First it replaces /**/ and /*\*/ with /~~/ and /~\~/ as these comments are used as CSS hacks and should stay in the file. Then it removes /*...*/ style comments on single lines (from Javascript and CSS files - this was adapted from a common PHP regular expression for removing CSS comments). Then it removes // style comments from Javascript files (unless they are preceded by a : which means they might be web links). (It's done in this order so that comments like /*...//...*/ get removed properly). Then it replaces all newlines with spaces and removes /*...*/ style comments again (this time over multiple lines). Then it puts the /**/ and /*\*/ CSS hacks back in. Then it replaces multiple spaces with single spaces. Then it removes spaces before [{;:,] and then spaces after [{:;,].

The command
The command is split over multiple lines. You can remove the \ to put it onto a single line.

sed -e "s|/\*\(\\\\\)\?\*/|/~\1~/|g" -e "s|/\*[^*]*\*\+\([^/][^*]*\*\+\)*/||g" \
  -e "s|\([^:/]\)//.*$|\1|" -e "s|^//.*$||" | tr '\n' ' ' | \
  sed -e "s|/\*[^*]*\*\+\([^/][^*]*\*\+\)*/||g" -e "s|/\~\(\\\\\)\?\~/|/*\1*/|g" \
  -e "s|\s\+| |g" -e "s| \([{;:,]\)|\1|g" -e "s|\([{;:,]\) |\1|g" 

Using the command
To use the command above, you have to pipe your CSS or Javascript into it, and save the output, like this:

cat myfile.css | sed ... > myfile-minimised.css

As a shell script
Or you can download this as a shell script too. Make it executable and then run it like this:

minify.sh myjavascript.js > myjavascript-minimised.js
minify.sh myfile-raw.css

In the second example, the script looks for -raw in the file name, and then a file named myfile.css is automatically created.

Problems - quotes and Ajaxy functions
This script does not ignore things in quotes. So if you have a comment inside a quote in a Javascript file, such as document.writeln ('//This is a comment');, the script will remove everything from the // and cause a Javascript error. Also, all lines of Javascript must end with a semicolon. This can be an issue with libraries which declare functions on a line but don't end the line with a semicolon (as is common in Ajax and JQuery scripts). For example, in: load : function (url,callback,format) {...} http.send(nul);, there should be a semicolon after the function definition. This is legal Javascript if there's a line break, but causes an error once minimised without the line break.