words | Gulp! One Task, Multiple Sources

Minify .html files and save them to different directories.

The Merge Stream package

We add each source (src) to a variable, then tell each source what to do, including where to be saved.

npm install --save-dev gulp gulp-minify-html merge-stream

The gulpfile.js file

// gulp, gulp-minify-html and merge-stream
var gulp = require('gulp'),
    minifyHTML = require('gulp-minify-html'),
    merge = require('merge-stream');

// minify HTML task      
gulp.task('minify-html', function() {
    var opts = {
      comments:true,
      spare:true
    };

    var myrootHTML = gulp.src('./*.html')
      .pipe(minifyHTML(opts))
      .pipe(gulp.dest('dist/'));
        
    var myprojectHTML = gulp.src('./projects/*.html')
      .pipe(minifyHTML(opts))
      .pipe(gulp.dest('dist/projects/'));    
        
    return merge(myrootHTML, myprojectHTML);
});

// task(s) to run with default command "gulp"
gulp.task('default', ['minify-html']);

Now when I run the command gulp this is my project structure

project-root-directory/
      
    index.html
    gulpfile.js
    package.json
  
    dist/  
        index.html
        projects/
            project.html
  
    node_modules/
        gulp
        gulp-minify-html
  
    projects/
        project.html

hmm...

I have a niggling feeling there is a more efficient way of doing this, it's just that I haven't found the time to look for it yet, but I will if it exists. Do I really need to keep adding every new source, and how do I avoid repeating lines of code, for example

.pipe(minifyHTML(opts))

This appears in both minify-html task variables!

The gulpfile.js file on this page is a basic example of a task and does only one thing

This will run with the default task command gulp

If you add more tasks (Sass, auto-prefix, watch, etc..), it can be run with it's own command gulp minify-html