Wednesday, January 16, 2013

perl Javascript and CSS minifier

During development I come across two interesting modules available on CPAN  Javascript::Minifier::XS and CSS::Minifier::XS both modules will help you during web development using perl cgi it has below listed features.

  • Both of them written in XS not in pure perl so its faster then traditional modules.
  • Javascript::Minifier::XS will remove unwanted or extra whitespace and comments from javascript it will take care of javascript will not get brake after minify process.
  • Same as javascript we have module for CSS and that will remove unwanted or extra whitespace and comments from CSS file by taking special care that functionality will net affect.
  • As far as production angle is concern we can combine our all Javascript/css file together and produce single output which will provides us facility to get all static content in single http call which will reduce your network traffic.
  • As per development angle your minify process get automated so we can avoid manual minification process and avoid risk of error. 
  • Developer can continue his development on original Javascript/CSS file.
Example for Javascript

test.js
$(function() {
    $( "#button" ).click(function(){
        $( ".newClass" ).switchClass( "newClass", "anotherNewClass", 1000 );
        $( ".anotherNewClass" ).switchClass( "anotherNewClass", "newClass", 1000 );
        return false;
    });
});
 
minify.pl
#! /usr/bin/perl
use strict;
use warnings;

use Javascript::Minifier::XS qw(minify);
# open javascript file file to read
open(INFILE, '<', 'test.js') or die $!;
my @content = <INFILE>;
close(INFILE) 

# minify file using Javascript::Minifier::XS
my $minified_js = minify(join('', @content));

open(OUTFILE, '>', 'test.min.js') or die $!;
print OUTFILE $minified_js;
close(OUTFILE);

Same way you can minify your CSS file with Javascript::CSS::XS. I would like to thanks Graham TerMarsch <cpan {at} howlingfrog {dot} com> for such a good development.