Search code examples
javascriptnode.jsgulp

Gulp multiple src


I am trying to inject a concatenated css file into my index.html using 'gulp-inject' and then version my files. I can get this working separately but what I am trying to do is compile everything in a single task so that I can run assetVersion() against certain files and the index.html. The problem I have is that my 'styles.min.css' is not written to disk and I'm not sure how to combine the streams to achieve my goal. Can anyone help?

gulp.task('compile',['clean'],function() { 

    // CSS - minify, concat to one file and copy
    gulp.src(paths.css + '*', { base: paths.base })
        .pipe(cleanCSS())
        .pipe(concat('styles.min.css'))
        .pipe(gulp.dest(paths.dist + paths.css));

    // Images - minify and copy
    gulp.src(paths.images + '*', { base: paths.base })
        .pipe(imagemin())
        .pipe(gulp.dest(paths.dist));

    // Index.html - inject the concatenated css, asset version and copy to dist
    gulp.src(paths.index)
        .pipe(inject(gulp.src(paths.dist + paths.css + 'styles.min.css', {read: false})))
        .pipe(debug())
        .pipe(assetVersion())
        .pipe(gulp.dest(paths.dist)); 

});

Solution

  • You can use run-sequence to force run each task synchronously.

    var runSequence = require('run-sequence')
    
    gulp.task('compile', ['clean'], function() {
        return runSequence(['compile:css', 'compile:images'], 'compile:version');
    });
    
    gulp.task('compile:css', function() {
    
        // CSS - minify, concat to one file and copy
        return gulp.src(paths.css + '*', { base: paths.base })
            .pipe(cleanCSS())
            .pipe(concat('styles.min.css'))
            .pipe(gulp.dest(paths.dist + paths.css));
    });
    
    gulp.task('compile:images', function() {
        // Images - minify and copy
        return gulp.src(paths.images + '*', { base: paths.base })
            .pipe(imagemin())
            .pipe(gulp.dest(paths.dist));
    });
    
    gulp.task('compile:version', function() {
        // Index.html - inject the concatenated css, asset version and copy to dist
        return gulp.src(paths.index)
            .pipe(inject(gulp.src(paths.dist + paths.css + 'styles.min.css', { read: false })))
            .pipe(debug())
            .pipe(assetVersion())
            .pipe(gulp.dest(paths.dist));
    });