Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automagically Minify CSS and Javascript on Upload

Does anyone know of a good way to automatically run certain file types through a processing script on upload? I'm trying to accomplish automatically minifying CSS and Javascript when I upload them to the server, keeping a nice, human-readable version on the local side while keeping a minified one on the server. I'm currently using WinSCP on Windows, which is scriptable to some degree but might not be scriptable enough. I'd probably need some kind of cobbled-together solution, so don't be afraid to suggest something with duct tape in it; however, I do need to do the minification on my local computer and upload the squished file, since I use shared hosting and can't install junk on the server.

Thanks.

like image 295
Jarett Millard Avatar asked Aug 31 '09 21:08

Jarett Millard


2 Answers

I recommend creating a makefile to solve this particular problem, here's a quick and dirty makefile I'm using for a site of mine:

PUBDIR=../../static/js/
OUTDIR=./build/
COMPRESSOR=../yui/build/yuicompressor-2.4.2.jar
ARGS=
VPATH=${OUTDIR}
INST_TARGETS=${OUTDIR}jgblue.js

jgblue.js: combined.js
    java -jar ${COMPRESSOR} ${ARGS} ${OUTDIR}$< -o ${OUTDIR}$@

combined.js: main.js listview.js tabs.js
    cat $^ > ${OUTDIR}$@

.PHONY: install

install:
    cp ${INST_TARGETS} ${PUBDIR}

Then all you have to type is:

make && make install

First it takes all of your development files and concatenates them into a single file, then the concatenated file gets compressed and copied into your public directory. I'm using YUICompressor for compression, it works quite well.

like image 94
William Casarin Avatar answered Oct 26 '22 15:10

William Casarin


Well, to minify CSS is just a couple of regexes.

// (PHP) but should be easily portable to any language
function compressCSS($css) {
    return
        preg_replace(
            array('@\s\s+@','@(\w+:)\s*([\w\s,#]+;?)@'),
            array(' ','$1$2'),
            str_replace(
                array("\r","\n","\t",' {','} ',';}'),
                array('','','','{','}','}'),
                preg_replace('@/\*[^*]*\*+([^/][^*]*\*+)*/@', '', $css)
            )
        )
    ;
}

And Dean Edwards's Javascript packer has been ported to PHP, Perl, .NET and WSH, so if you're using any of those technologies, you could actually have it running on your own server. ...Just remember to cache the results!

like image 23
nickf Avatar answered Oct 26 '22 14:10

nickf