Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Gulp watch to perform function only on changed file

I am new to Gulp and have the following Gulpfile

var gulp = require('gulp');
var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');

gulp.task('compress', function () {
    return gulp.src('js/*.js') // read all of the files that are in js with a .js extension
      .pipe(uglify()) // run uglify (for minification)
      .pipe(gulp.dest('dist/js')); // write to the dist/js file
});

// default gulp task
gulp.task('default', function () {

    // watch for JS changes
    gulp.watch('js/*.js', function () {
        gulp.run('compress');
    });

});

I would like to configure this to rename, minify and save only my changed file to the dist folder. What is the best way to do this?

like image 251
bmdeveloper Avatar asked Feb 16 '15 16:02

bmdeveloper


People also ask

How does a gulp Watch work?

The Watch method is used to monitor your source files. When any changes to the source file is made, the watch will run an appropriate task. You can use the 'default' task to watch for changes to HTML, CSS, and JavaScript files.

How do you stop a gulp watch?

Gulp is just running as a never ending process. The way to abort a process is Ctrl + C .

Is gulp better than Webpack?

The performance is not faster while comparing with other applications. But as this handles more applications within itself, it cannot keep the tasks in-memory. Gulp is used less, and the users do not prefer much the application. Webpack is preferred by the users and is older than Gulp.


1 Answers

This is how:

// Watch for file updates
gulp.task('watch', function () {
    livereload.listen();

    // Javascript change + prints log in console
    gulp.watch('js/*.js').on('change', function(file) {
        livereload.changed(file.path);
        gutil.log(gutil.colors.yellow('JS changed' + ' (' + file.path + ')'));
    });

    // SASS/CSS change + prints log in console
    // On SASS change, call and run task 'sass'
    gulp.watch('sass/*.scss', ['sass']).on('change', function(file) {
        livereload.changed(file.path);
        gutil.log(gutil.colors.yellow('CSS changed' + ' (' + file.path + ')'));
    });

});

Also great to use gulp-livereload with it, you need to install the Chrome plugin for it to work btw.

like image 58
Leon Gaban Avatar answered Sep 18 '22 17:09

Leon Gaban