Closure Compiler JS - CSS Transform into a bulk process

4

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

To run the build process I can do the following:

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

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

The first thing I did was go through the entire directory where JS is 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 returns 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 complete 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 output goes 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 questions?

1 ° to make a foreach of the root without leaving subArrays and how? if I make a foreach the result goes like this:

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

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

3 ° There is some tool that simplifies this whole process, my need is just to be able to select a directory that contains the files in which I want to minify.

    
asked by anonymous 07.07.2015 / 15:52

1 answer

2

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

I prefer Gulp , it's much easier. Both Gulp and Grunt will dispense with any backward programming work, as in your case, you will not need to create any array or whatever the background work of listing these files.

What are they and what are they for?

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

How to use Gulp ?

  • Install Node.js ( link )
  • In MS-DOS (Windows) or Shell (Linux), install Gulp :

    npm install -g gulp

  • To verify that you have installed, see if the version is displayed:

    gulp -v

  • Suppose you have the following directory structure:

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

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

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

  • Note that the Gulp DE NOVO was installed 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 installed this time is the place that is used to run the tests in 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');
        });
    
    });
    
  • All lines are commented out. Simply insert the source directories of your js . Now run Gulp :

    gulp

  • The above command will execute Gulp for all tasks in Gulpfile.js . If you want to run a specific task (from a plugin installed above that you entered in Gulpfile.js ), run:

    gulp tarefa (ex: gulp dist ).

    Summary

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

    The full list of plugins for Gulp you can look at: link .

    Tip : install the minificador de css plugin: link

    Complete tutorial: here .

        
    07.07.2015 / 18:41