There are some tools can be used to minify your js and css files, such as JSMIN, Dojo compressor, Edwards' Packer and YUI Compressor. Since I was using YUI these days, I decide to choose YUI Compressor to do this job.
The first solution comes into my mind is to create a Grails Script to process js and css files by "grails create-script". On second thought, I think this is not an appropriate one:
- If it changes the name of js or css files, you have to change the corresponding files name in your frontend source code. This is annoying and error-prone.
- If it doesn't change the files' name, it will modify the content of js and css source files. This can also make you unhappy: facing a minified js and css files, you can even hardly change the name of a variable. It is a big problem!
Since we know how to do it, let's do it:
- Downloading YUI Compressor,which usage is simple:"java -jar yuicompressor-x.x.x.jar inputfile -o outputfile".
- Unzipping it and copying YUI Compressor binary to lib directory in your grails project.
- Creating a "_Event.groovy" in your grails project's script directory:
eventCreateWarStart = { warLocation, stagingDir ->
stagingDir.eachFileRecurse{
if(it.name.endsWith('.js')||it.name.endsWith('.css')){
def f= it.absolutePath
println "Minizing ${f}......................"
ant.java(jar:"${basedir}/lib/yuicompressor-2.4.2.jar",
fork: true){
arg(value: "${f}")
arg(value: "-o")
arg(value: "${f}")
}
println "Minizing ${f}.................done!"
}
}
}
Another interesting thing is: if there are some errors in your javascript source, YUI Compressor won't minify it(this won't break the build process). So you get an additional checking javascript function ;). Hope you enjoy it!
3 comments:
You should look at the UI Performance plugin, it does this and a lot more: http://grails.org/plugin/ui-performance
@Burt
Thanks, that plugin seems great! I will check it out!
good work ...
Post a Comment