Search code examples
javascriptgulpbrowser-syncgulp-uglifygulp-rename

How do I make a min file in the same path or dest on gulp-rename and gulp-uglify?


Hi everyone I hope you having a great day, I'm trying to find a way on how do I make a min file in the same path or gulp.dest() on gulp(gulp-uglify and gulp-rename). In my code below when I run my gulp it keeps on creating *.min.js , *.min.min.js , *.min.min.min.js so on and so forth unless I stop the terminal. How do I make my gulp create only one *.min.js at the same time it uglify's. I hope everyone can help me with this one. Thank You.

const gulp = require('gulp');
const browserSync = require('browser-sync').create();
const rename = require('gulp-rename');
const uglify = require('gulp-uglify');

gulp.task('scripts', function() {
    return gulp.src('./src/js/*.js')       
        .pipe(uglify())
        .pipe(rename( {suffix: '.min'} ))
        .pipe(gulp.dest('./src/js/'))
        .pipe(browserSync.stream());
});

gulp.task('browserSync', function(){

    browserSync.init({
        server : {
            baseDir : './'
        }
    });
    gulp.watch('./src/js/**.js', gulp.series('scripts'));
});

gulp.task('default', gulp.series('scripts', 'browserSync'));

Solution

  • This is happening because your scripts task is outputting the files to the same directory as you are watching:

    .pipe(gulp.dest('./src/js/'))
    

    and

    gulp.watch('./src/js/**.js', gulp.series('scripts'));
    

    So every time scripts runs and saves to that directory it triggers your watch again which fires scripts, etc., etc.

    So either save your .min's to a directory you are not watching or don't watch .min files.

    BTW, change to gulp.watch('./src/js/*.js', gulp.series('scripts')); // removed one asterisk

    gulp.watch(['./src/js/*.js', '!./src/js/*.min.js'], gulp.series('scripts')); // might work - untested though.