Closure Compiler JS - CSS Transform into a Bulk Process

Asked

Viewed 95 times

5

Google has two tools for compilar/minificar optimizing the files JS and CSS, Closure Compiler JS and Closure Compiler CSS.

To perform the compilation process I can do as follows:

java -jar compiler.jar --js hello.js --js_output_file hello-compiled.js

Currently I use a file .bat with 40 lines that were created manually for minificar the files, and as the system grows and new files arise sometimes I forget to include new files in that bat, so I thought to make a process to create these paths.

The first thing I did was go through the whole directory where the JS and save the files in an array:

function dirToArray($dir) {
   $result = array();
   $cdir = scandir($dir);
   $raiz = '';
   foreach ($cdir as $key => $value) {
      if (!in_array($value, array(".", ".."))) {
         if (is_dir($dir . DIRECTORY_SEPARATOR . $value) && ($value !== "lib")) {
            $result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value);
            $raiz = $value;
         } elseif (strrchr($value, '.') === ".js") {
            $result[] = $value;
         }
      }
   }
   return $result;
}

$dir = '../../controller/js';
$files = dirToArray($dir);

This way return me an array:

array
  0 => string 'agenda.js' (length=9)
  1 => string 'agendaNegoc.js' (length=14)
  2 => string 'atribCobrador.js' (length=16)
  3 => string 'atualizaSistema.js' (length=18)
  'cadastro' => 
    array
      0 => string 'agencia.js' (length=10)
      1 => string 'avisos.js' (length=9)
      2 => string 'bancoEmpresa.js' (length=15)
      3 => string 'cidade.js' (length=9)
      4 => string 'cliente.js' (length=10)
      5 => string 'cobradores.js' (length=13)
      6 => string 'codEventos.js' (length=13)
      7 => string 'remessa.js' (length=10)
  4 => string 'comercial.js' (length=15)
  5 => string 'controleCobranca.js' (length=22)
  6 => string 'classCliente.js' (length=15)
  7 => string 'cliente.js' (length=10)
  8 => string 'codigosEventos.js' (length=17)
  9 => string 'consultaWebservice.js' (length=27)
  10 => string 'coresSistema.js' (length=15)
  11 => string 'dadosCliente.js' (length=15)
  12 => string 'detalhesOperacao.js' (length=19)
  13 => string 'emissaoboleto.js' (length=16)
  14 => string 'enviarEmail.js' (length=14)
  15 => string 'exportador.js' (length=13)
  16 => string 'fases.js' (length=14)
  17 => string 'filtroNivelUsuario.js' (length=21)
  18 => string 'funcoes.js' (length=10)
  'importador' => 
    array
      0 => string 'importadorAS1.js' (length=18)
  20 => string 'importador.js' (length=13)
  21 => string 'importador_exportador.js' (length=24)
  22 => string 'inserirAgendamento.js' (length=21)
  23 => string 'inserirEventos.js' (length=17)
  24 => string 'listaUsuarios.js' (length=16)
  25 => string 'login.js' (length=8)
  26 => string 'mensagemInterna.js' (length=24)
  27 => string 'menu.js' (length=7)
  28 => string 'motivosPausa.js' (length=15)
  'negociacao' => 
    array
      0 => string 'cobrancaA.js' (length=19)
      1 => string 'cobrancaB.js' (length=22)
      2 => string 'cobrancaB2.js' (length=28)
      3 => string 'cobrancaC3.js' (length=25)
      4 => string 'cobrancaM.js' (length=18)
      5 => string 'codEvento.js' (length=12)
      6 => string 'propostaAnexos.js' (length=22)
  29 => string 'notificador.js' (length=14)
  30 => string 'origemdb.js' (length=11)
  31 => string 'permissoes.js' (length=13)
  32 => string 'pesquisaCliente.js' (length=18)
  'portal' => 
    array
      0 => string 'negociacao.js' (length=13)
  33 => string 'referenciasPessoais.js' (length=22)
  'relatorio' => 
    array
      0 => string 'filtroDemonstrativo.js' (length=28)
      1 => string 'filtroRelBol.js' (length=18)
      2 => string 'filtroRelEventos.js' (length=19)
      3 => string 'filtroRelPrestContas.js' (length=23)
      4 => string 'relDemonsDebito.js' (length=18)
      5 => string 'relEventos.js' (length=13)
  34 => string 'supervisorLista.js' (length=18)
  35 => string 'usuarioBanco.js' (length=15)

So I created a function to generate the full path:


function geraPatch($files, $param, $devPatch, $prodPatch) {
   $result = array();

   foreach ($files['cadastro'] as $key => $value) {
      $result['cadastro'][$key] = $param . $devPatch . 'cadastro/' . $value . $prodPatch . 'cadastro/' . $value;
   }

   foreach ($files['importador'] as $key => $value) {
      $result['importador'][$key] = $param . $devPatch . 'importador/' . $value . $prodPatch . 'importador/' . $value;
   }

   foreach ($files['negociacao'] as $key => $value) {
      $result['negociacao'][$key] = $param . $devPatch . 'negociacao/' . $value . $prodPatch . 'negociacao/' . $value;
   }

   foreach ($files['portal'] as $key => $value) {
      $result['portal'][$key] = $param . $devPatch . 'portal/' . $value . $prodPatch . 'portal/' . $value;
   }
   foreach ($files['relatorio'] as $key => $value) {
      $result['relatorio'][$key] = $param . $devPatch . 'relatorio/' . $value . $prodPatch . 'relatorio/' . $value;
   }
   return $result;
}

$dir = '../../controller/js';
$files = dirToArray($dir);
$param = 'java -jar compiler.jar --js ';
$devPatch = 'desenvolvimento/';
$prodPatch = ' --js_output_file producao/';

var_dump(geraPatch($files, $param, $devPatch, $prodPatch));

And the result comes out as expected

 0 => string 'java -jar compiler.jar --js desenvolvimento/cadastro/agencia.js --js_output_file producao/cadastro/agencia.js' (length=109)
      1 => string 'java -jar compiler.jar --js desenvolvimento/cadastro/avisos.js --js_output_file producao/cadastro/avisos.js' (length=107)
      2 => string 'java -jar compiler.jar --js desenvolvimento/cadastro/bancoEmpresa.js --js_output_file producao/cadastro/bancoEmpresa.js' (length=119)
      3 => string 'java -jar compiler.jar --js desenvolvimento/cadastro/cidade.js --js_output_file producao/cadastro/cidade.js' (length=107)
      4 => string 'java -jar compiler.jar --js desenvolvimento/cadastro/cliente.js --js_output_file producao/cadastro/cliente.js' (length=109)

What are my doubts?

1° to make a foreach from the root without leaving the subArrays and how ? if I make one foreach the result comes out like this:

java -jar compiler.jar --js desenvolvimento/Array --js_output_file producao/Array

2° How can I get all this array configured and create a file in php .bat and save all that text to run it ?

3° Is there any tool that simplifies this whole process, my need is precisely to be able to select a directory that contains the files in which I want to minify.

1 answer

2


Working with repetitive tasks in scripts JS and CSS made it much easier with the coming of Grunt and of Gulp.

I prefer the Gulp, It’s a lot easier. Both Gulp and Grunt will dispense with any programming work behind it, as in your case, in which you will not need to create an array or whatever the background work of preparing the listing of these files.

What they are and what they’re for?

Task Automators are tools that help [lazy hehe] programmers perform repetitive but essential development tasks such as: file concatenation, minification, testing and many other things needed to create a fast and efficient code.

How to use the Gulp?

  1. Install the Node.js (https://nodejs.org/download/)
  2. In the MS-DOS (Windows) or on Shell (Linux), install the Gulp:

    npm install -g gulp

  3. To check if you have installed, see if the version is displayed:

    gulp -v

  4. Let’s assume that you have the following directory structure:

    |projeto/ |--dist/ |--src/ |----source.js |--Gulpfile.js

  5. Install the plugins of contatenação, minificação and that of renomeação (which is what you need):

    npm install gulp gulp-jshint gulp-uglify gulp-concat gulp-rename --save-dev

  6. Note that it was installed itself Gulp AGAIN next to the plugins. This is because the Gulp previously installed was the CLI, responsible for running the command gulp on the command line and the one installed this time is the location that is used to run the tests on the project. Now we can edit our Gulpfile.js:

Gulpfile.js

// Aqui nós carregamos o gulp e os plugins através da função `require` do nodejs
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var rename = require('gulp-rename');

// Definimos o diretorio dos arquivos para evitar repetição futuramente
var files = "./src/*.js";

//Aqui criamos uma nova tarefa através do ´gulp.task´ e damos a ela o nome 'lint'
gulp.task('lint', function() {

    // Aqui carregamos os arquivos que a gente quer rodar as tarefas com o `gulp.src`
    // E logo depois usamos o `pipe` para rodar a tarefa `jshint`
    gulp.src(files)
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

//Criamos outra tarefa com o nome 'dist'
gulp.task('dist', function() {

    // Carregamos os arquivos novamente
    // E rodamos uma tarefa para concatenação
    // Renomeamos o arquivo que sera minificado e logo depois o minificamos com o `uglify`
    // E pra terminar usamos o `gulp.dest` para colocar os arquivos concatenados e minificados na pasta build/
    gulp.src(files)
    .pipe(concat('./dist'))
    .pipe(rename('dist.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest('./dist'));

});

//Criamos uma tarefa 'default' que vai rodar quando rodamos `gulp` no projeto
gulp.task('default', function() {

    // Usamos o `gulp.run` para rodar as tarefas
    // E usamos o `gulp.watch` para o Gulp esperar mudanças nos arquivos para rodar novamente
    gulp.run('lint', 'dist');
    gulp.watch(files, function(evt) {
        gulp.run('lint', 'dist');
    });

});
  1. All lines are commented on. Just enter the source directories of your js. Now turn the Gulp:

    gulp

The above command will execute the Gulp for all tasks in the Gulpfile.js. If you wish to perform a specific task (from a plugin installed above and which you have entered into Gulpfile.js), spin:

gulp tarefa (ex.: gulp dist).

Summary

The idea is simple: create a file Gulpfile.js, insert the tasks of your plugins Gulp, choose the files and directories of your scripts and finally run the Gulp.

The complete list of plugins for Gulp you can see in: http://gulpjs.com/plugins/.

Tip: install the plugin minificador de css: https://npmjs.org/package/gulp-minify-css/

Full tutorial: here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.