Gulp Watch Custom

2

This is my current Gulpfile and as I am using it a lot, I would like to create a GULP WATCH that would perform uglify whenever the files were changed.

var gulp = require('gulp');
var uglify = require('gulp-uglify');
var pump = require('pump');

gulp.task('compress', function (cb) {
  console.log("Compressing the Source");
  pump([
        gulp.src('source/*.js'),
        uglify(),
        gulp.dest('assets/js')
    ]
  );
  console.log("Source Compressed");
  console.log("Compressing AngularJS");
  pump([
        gulp.src('bower_components/angular/angular.js'),
        uglify(),
        gulp.dest('assets/js')
    ]
  );
  console.log("Compressing AngularJS Animate");
  pump([
        gulp.src('bower_components/angular-animate/angular-animate.js'),
        uglify(),
        gulp.dest('assets/js')
    ],
    cb
  );
});

Tips for improving the process are also welcome.

    
asked by anonymous 08.02.2017 / 18:50

1 answer

4

As already said in the comment, to create the "watch" it is only necessary to create a new task containing a% of the tasks that you want to be executed when modifying the file:

gulp.task('watch', () => gulp.watch(
    ['caminho/do_arquivo.js', 'outro_caminho.js'], 
    ['task1', 'task2' ]
))

I noticed that all of your javascript files are going to the same place gulp.watch , so it would be good to just create a single task for these files and use an array in assets/js , as it gets easier if you want to put a sass or something like . And since the path must be repeated in watch , another tip is to use a variable with the paths instead of typing them 2 times.

Resulting in:

var gulp = require('gulp');
var uglify = require('gulp-uglify');
var pump = require('pump');

var jspaths = [
    'source/*.js',
    'bower_components/angular/angular.js',
    'bower_components/angular-animate/angular-animate.js',
    // Se quiser todos os arquivos dentro de "bower_components" (não recomendo) pode usar
    // 'bower_components/**/*.js',
];

gulp.task('jscompress', (cb) => {
    pump([
        gulp.src(jspaths),
        uglify(),
        gulp.dest('assets/js')
    ], cb);
});


gulp.task('watch', () => gulp.watch(jspaths, [
    'jscompress'
]))

Then just give .src to gulp watch and be happy! xD

Or you can rename the task console to gulp.task('watch',... and just type gulp.task('default',... into console .

One note was that I removed the logs , they are unnecessary considering that the gulp itself will report which task started and ended.     

09.02.2017 / 03:03