simple css minify
updated: 2007-12-05
i've posted an update for cssminify to improve whitespace handling.
updated: 2007-10-24
i've posted my server-side script (conflate.ashx) that combines multiple CSS documents into a single result - all 'on the fly.'
i've been using CSSTidy recently and really like it. however, i ran into a problem with it this week while using the YUI Grids CSS files. CSSTidy removes several CSS hacks from the YUI files rendering them useless. first, boo for hacks. second, boo for CSSTidy not allowing me to adjust.
so i whipped up a simple CSS minify routine for my own use. this does not do the cool tidy work that CSSTidy does, but at least it plays well with the YUI stuff. this simple command-line routine lets me supply an input file and (optionally) an output filename and single-line comment. i get about 30% reduction just by removing comments and un-needed whitespace. not too bad.
btw - please excuse the VBScript[g]. i was in a hurry!
' ***************************************************
' cssminify.vbs
' 2007-10-03 (mca)
' remove comments and whitespace from CSS files
' no tidying up here, just minifying
' usage:
' cssminify infile.css [outfile.css] ["comment"]
' ***************************************************
' vars
Dim fso,f,cmt,rex,data,re_cmt,re_ws,ifile,ofile
re_cmt = "/\*[\s\S]*?\*/"
re_ws = "[\r\n\t]*"
' get input file
If WScript.Arguments.Count=0 Then
WScript.Echo "Missing Input File"
WScript.Quit
Else
ifile = WScript.Arguments.Item(0)
End If
' get output file (or set default)
If WScript.Arguments.Count>1 Then
ofile = WScript.Arguments.Item(1)
Else
ofile = "min-" & WScript.Arguments.Item(0)
End If
' get comment line
If WScript.Arguments.Count=3 Then
cmt = "/* " & WScript.Arguments.Item(2) & " */"
Else
cmt = ""
End If
' set file object
Set fso = CreateObject("Scripting.FileSystemObject")
' read data in
Set f = fso.OpenTextFile(ifile,1,False)
data = f.ReadAll()
f.Close
Set f = Nothing
' do regexp work
Set rex = new RegExp
rex.MultiLine = True
rex.Global = True
rex.Pattern = re_cmt
data = rex.Replace(data,"")
rex.Pattern = re_ws
data = rex.Replace(data,"")
Set rex = Nothing
' write data out
Set f = fso.CreateTextFile(ofile,1,False)
f.WriteLine("/* cssminify @ " & Now() & " */")
If cmt<>"" Then f.WriteLine(cmt)
f.Write(data)
f.Close
Set f = Nothing
' all done
WScript.Quit