Dieses Perl-Skript komprimiert JavaScript- und CSS-Dateien.
#!/usr/bin/perl -w
use strict;
use lib "./Module/"; # include folder to searching for Modules
use open ':utf8';
use File::Basename;
my $outfile = "";
if(scalar(@ARGV) == 0) {
die "usage: '$0 <filename>'\n\n";
}
my $infile = $ARGV[0];
$outfile = $infile;
$outfile =~ s|\bdata/|www/|g;
my($outfilename, $outdir, $ext) = fileparse($outfile, qr/\.[^.]+$/);
if(!-e $outdir) {
use File::Path;
File::Path::make_path($outdir, {
verbose => 1,
mode => 0777
});
}
my $type = "";
if($ext eq ".js" || $ext eq ".css" || $ext eq ".html" || $ext eq ".xml") {
$type = "text";
}
elsif($ext eq ".png") {
$type = "image";
}
else {
use File::Copy;
print "can't compress '" . $ext . "', just copying\n";
copy($infile, $outfile) or die "copy failed: $!";
exit;
}
my $str = '';
if($type eq "text") {
open FH_CONTENT, $infile or die "unable to open '$infile', $!";
while (<FH_CONTENT>) {
$str .= $_;
}
close FH_CONTENT;
}
if($ext eq ".js") {
use JavaScript::Minifier qw(minify);
$str = minify(input => $str);
}
elsif($ext eq ".css") {
$str =~ s|^\s+||g;
$str =~ s|\s+$||g;
$str =~ s|(\s){2,}| |g;
$str =~ s|/\*.*?\*/||g;
$str =~ s|\n||g;
$str =~ s|,\s+|,|g;
$str =~ s|\s*{\s*|{|g;
$str =~ s|\s*}\s*|}|g;
$str =~ s|\s*;\s*|;|g;
$str =~ s|;}|}|g;
}
elsif($ext eq ".html" || $ext eq ".xml") {
use HTML::Packer;
my $packer = HTML::Packer->init();
$packer->minify(\$str, {
'remove_newlines' => 1
});
}
elsif($ext eq ".png") {
`pngcrush -reduce $infile $outfile` or die "unable to compress '$infile' with pngcrush, stopped at $!";
}
if($type eq "text") {
open FH_OUT, ">" . $outfile or die "unable to open '$outfile' for write, $!";
print FH_OUT $str . "\n";
close FH_OUT;
}
my $oldbytes = sprintf("%.2f", (-s $infile)/1000);
my $newbytes = sprintf("%.2f", (-s $outfile)/1000);
print "compressed " . $outfile . " (" . $oldbytes . "kB to " . $newbytes . "kB)\n\n";