INTRODUÇÃO
Para esta tarefa existem dezenas de ferramentas online, mas o objetivo do artigo é apresentar formas de obter o mesmo resultado a partir do terminal GNU/Linux, afinal de contas nada é mais produtivo que a boa e velha tela preta!
CLEAN-CSS
Nesta página vamos conhecer o clean-css, ferramenta usada para minimizar arquivos CSS e que está disponível nos repositórios das principais distribuições.
Para instalar em Debian/Ubuntu e derivados:
$ sudo apt-get install cleancss
Não testei em outras distribuições, caso não encontre o pacote, baixe-o pelo GitHub:
NOTA: clean-css depende do Node.js para ser instalado.
Alternativamente, se você já tiver o Node.js instalado no sistema, pode instalar o clean-css pelo npm:
$ sudo npm install clean-css
MINIMIZANDO CSS
A melhor forma de explicar o funcionamento da ferramenta é com exemplos práticos, então vamos lá!
Supondo que você tenha uma folha de estilo chamada estilo.css com o seguinte conteúdo:
body {
padding-left: 11em;
font-family: Georgia, "Times New Roman", Times, serif;
color: purple;
background-color: #d8da3d
}
ul.navbar {
list-style-type: none;
padding: 0;
margin: 0;
position: absolute;
top: 2em;
left: 1em;
width: 9em
}
h1 {
font-family: Helvetica, Geneva, Arial, SunSans-Regular, sans-serif
}
ul.navbar li {
background: white;
margin: 0.5em 0;
padding: 0.3em;
border-right: 1em solid black
}
ul.navbar a {
text-decoration: none
}
a:link {
color: blue
}
a:visited {
color: purple
}
address {
margin-top: 1em;
padding-top: 1em;
border-top: thin dotted
}
Para minimizá-la faremos:
$ cleancss -o estilo-min.css estilo.css
Como saída (-o) teremos o arquivo estilo-min.css, que ficará assim:
body{padding-left:11em;font-family:Georgia,"Times New Roman",Times,serif;color:purple;background-color:#d8da3d}ul.navbar{list-style-type:none;padding:0;margin:0;position:absolute;top:2em;left:1em;width:9em}h1{font-family:Helvetica,Geneva,Arial,SunSans-Regular,sans-serif}ul.navbar li{background:#fff;margin:.5em 0;padding:.3em;border-right:1em solid #000}ul.navbar a{text-decoration:none}a:link{color:#00f}a:visited{color:purple}address{margin-top:1em;padding-top:1em;border-top:thin dotted}
Outras formas de uso:
$ cleancss estilo.css
$ cleancss estilo.css > estilo-min.css
$ cat estilo1.css estilo2.css estilo3.css | cleancss -o estilo-todos-min.css
Fonte: https://github.com/jakubpawlowicz/clean-css
Na próxima página veremos como otimizar arquivos Javascript.
JAVASCRIPT-MINIFIER
Partindo do princípio de que já tenha o Perl instalado em seu sistema, o próximo passo é instalar o módulo.
Em Debian/Ubuntu e derivados isso pode ser feito com o seguinte comando:
$ sudo apt-get install libjavascript-minifier-perl
Nas demais distribuições (incluindo Debian/Ubuntu), é possível instalar o módulo usando o shell CPAN:
$ sudo perl -MCPAN -e shell
cpan> install JavaScript::Minifier
Leitura recomendada: A forma correta de se instalar módulos Perl [Artigo]
Agora vamos criar o Perl script que será usado para minimizar arquivos JS:
$ sudo vim /usr/local/bin/jsmin.pl
#!/usr/bin/perl
my $source = shift;
if (! -f $source) {
print "Use: $0 <input-file>\n\n";
}
use JavaScript::Minifier qw(minify);
open(INFILE, $source) or die;
print minify(input => *INFILE);
close(INFILE);
Salve e saia. O código, além de ser auto-explicativo, não é o foco do artigo. Apenas transcreva-o e em seguida torne-o executável:
$ sudo chmod a+x /usr/local/bin/jsmin.pl
Pronto! Já podemos usar o comando jsmin.pl para minimizar nossos scripts. Exemplo:
$ jsmin.pl app.js > app-min.js
Compare o código original com o código gerado e veja a diferença:
/* app.js original */
/*
* Template Name: Unify - Responsive Bootstrap Template
* Description: Business, Corporate, Portfolio, E-commerce and Blog Theme.
* Version: 1.6
* Author: @htmlstream
* Website: http://htmlstream.com
*/
var App = function () {
//Bootstrap Tooltips and Popovers
function handleBootstrap() {
/*Bootstrap Carousel*/
jQuery('.carousel').carousel({
interval: 15000,
pause: 'hover'
});
/*Tooltips*/
jQuery('.tooltips').tooltip();
jQuery('.tooltips-show').tooltip('show');
jQuery('.tooltips-hide').tooltip('hide');
jQuery('.tooltips-toggle').tooltip('toggle');
jQuery('.tooltips-destroy').tooltip('destroy');
/*Popovers*/
jQuery('.popovers').popover();
jQuery('.popovers-show').popover('show');
jQuery('.popovers-hide').popover('hide');
jQuery('.popovers-toggle').popover('toggle');
jQuery('.popovers-destroy').popover('destroy');
}
//Search Box (Header)
function handleSearch() {
jQuery('.search').click(function () {
if(jQuery('.search-btn').hasClass('fa-search')){
jQuery('.search-open').fadeIn(500);
jQuery('.search-btn').removeClass('fa-search');
jQuery('.search-btn').addClass('fa-times');
} else {
jQuery('.search-open').fadeOut(500);
jQuery('.search-btn').addClass('fa-search');
jQuery('.search-btn').removeClass('fa-times');
}
});
}
//Sidebar Navigation Toggle
function handleToggle() {
jQuery('.list-toggle').on('click', function() {
jQuery(this).toggleClass('active');
});
/*
jQuery('#serviceList').on('shown.bs.collapse'), function() {
jQuery(".servicedrop").addClass('glyphicon-chevron-up').removeClass('glyphicon-chevron-down');
}
jQuery('#serviceList').on('hidden.bs.collapse'), function() {
jQuery(".servicedrop").addClass('glyphicon-chevron-down').removeClass('glyphicon-chevron-up');
}
*/
}
//Fixed Header
function handleHeader() {
jQuery(window).scroll(function() {
if (jQuery(window).scrollTop()>100){
jQuery(".header-fixed .header-sticky").addClass("header-fixed-shrink");
}
else {
jQuery(".header-fixed .header-sticky").removeClass("header-fixed-shrink");
}
});
}
//Header Mega Menu
function handleMegaMenu() {
jQuery(document).on('click', '.mega-menu .dropdown-menu', function(e) {
e.stopPropagation()
})
}
return {
init: function () {
handleBootstrap();
handleSearch();
handleToggle();
handleHeader();
handleMegaMenu();
},
//Clients Logo
initSliders: function () {
jQuery('#clients-flexslider').flexslider({
animation: "slide",
easing: "swing",
animationLoop: true,
itemWidth: 1,
itemMargin: 1,
minItems: 2,
maxItems: 9,
controlNav: false,
directionNav: false,
move: 2
});
jQuery('#clients-flexslider1').flexslider({
animation: "slide",
easing: "swing",
animationLoop: true,
itemWidth: 1,
itemMargin: 1,
minItems: 2,
maxItems: 5,
controlNav: false,
directionNav: false,
move: 2
});
jQuery('#photo-flexslider').flexslider({
animation: "slide",
controlNav: false,
animationLoop: false,
itemWidth: 80,
itemMargin: 0
});
jQuery('#testimonal_carousel').collapse({
toggle: false
});
},
//Counters
initCounter: function () {
jQuery('.counter').counterUp({
delay: 10,
time: 1000
});
},
//Parallax Backgrounds
initParallaxBg: function () {
jQuery(window).load(function() {
jQuery('.parallaxBg').parallax("50%", 0.2);
jQuery('.parallaxBg1').parallax("50%", 0.4);
});
},
};
}();
E o resultado:
/* app-min.js */
var App=function(){function handleBootstrap(){jQuery('.carousel').carousel({interval:15000,pause:'hover'});jQuery('.tooltips').tooltip();jQuery('.tooltips-show').tooltip('show');jQuery('.tooltips-hide').tooltip('hide');jQuery('.tooltips-toggle').tooltip('toggle');jQuery('.tooltips-destroy').tooltip('destroy');jQuery('.popovers').popover();jQuery('.popovers-show').popover('show');jQuery('.popovers-hide').popover('hide');jQuery('.popovers-toggle').popover('toggle');jQuery('.popovers-destroy').popover('destroy');}
function handleSearch(){jQuery('.search').click(function(){if(jQuery('.search-btn').hasClass('fa-search')){jQuery('.search-open').fadeIn(500);jQuery('.search-btn').removeClass('fa-search');jQuery('.search-btn').addClass('fa-times');}else{jQuery('.search-open').fadeOut(500);jQuery('.search-btn').addClass('fa-search');jQuery('.search-btn').removeClass('fa-times');}});}
function handleToggle(){jQuery('.list-toggle').on('click',function(){jQuery(this).toggleClass('active');});}
function handleHeader(){jQuery(window).scroll(function(){if(jQuery(window).scrollTop()>100){jQuery(".header-fixed .header-sticky").addClass("header-fixed-shrink");}
else{jQuery(".header-fixed .header-sticky").removeClass("header-fixed-shrink");}});}
function handleMegaMenu(){jQuery(document).on('click','.mega-menu .dropdown-menu',function(e){e.stopPropagation()})}
return{init:function(){handleBootstrap();handleSearch();handleToggle();handleHeader();handleMegaMenu();},initSliders:function(){jQuery('#clients-flexslider').flexslider({animation:"slide",easing:"swing",animationLoop:true,itemWidth:1,itemMargin:1,minItems:2,maxItems:9,controlNav:false,directionNav:false,move:2});jQuery('#clients-flexslider1').flexslider({animation:"slide",easing:"swing",animationLoop:true,itemWidth:1,itemMargin:1,minItems:2,maxItems:5,controlNav:false,directionNav:false,move:2});jQuery('#photo-flexslider').flexslider({animation:"slide",controlNav:false,animationLoop:false,itemWidth:80,itemMargin:0});jQuery('#testimonal_carousel').collapse({toggle:false});},initCounter:function(){jQuery('.counter').counterUp({delay:10,time:1000});},initParallaxBg:function(){jQuery(window).load(function(){jQuery('.parallaxBg').parallax("50%",0.2);jQuery('.parallaxBg1').parallax("50%",0.4);});},};}();
Fonte: http://search.cpan.org/~pmichaux/JavaScript-Minifier-1.05/lib/JavaScript/Minifier.pm
É isso!