Search This Blog

Friday 8 April 2016

How to pass parameters to a gulp task within the gulpfile

There is information out there, how to pass a parameter on a command line when running a gulp task. The example here shows how to pass a parameter from one task to another within the gulpfile.

Tested on Ubuntu 15.04 using node@4.4.2.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
'use strict';
/*
 * performs a build task of uglifying and concatenating txt files in the top subdirectories
 * the built files are deposited in build directory of each top subdirectory
 *
 * the challenge was in passing a variable to a task
 *
 * works with node@4.4.2, gulp (CLI version 1.2.1, Local version 3.9.1)
 * 
 */
const gulp = require('gulp');

const fs = require('fs');
const path = require('path');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const notify = require('gulp-notify');
const _ = require('lodash');
const async = require('async');

// Function variable containing the processing task
// ------------------------------------------------
//      Process task needs to be performed on every given subdirectory.
//      For that the full path, that dynamically changes, is required.
//      The task is wrapped in a function, that accepts a subdirectory parameter,
//      which is then available to the task.
//      
const subdirTask = (subdirPath, cb) => {
    // if the result is to live in ./build/${sundirectory} => get the subdirectory from the path
    //      const basename = path.basename(subdirPath);
    
    // Define the processing task
    // --------------------------
    gulp.task('process', () => {
      // selects files to act on
      return gulp.src(`${subdirPath}/*.txt`)
        // does what needs to be done 
        .pipe(uglify())
        .pipe(concat('all.txt'))
        // puts the result in the the specified place 
        .pipe(gulp.dest(`${subdirPath}/build`))
        // notifies that work was done
        .pipe(notify(`... Finished processing ${subdirPath}`));
    });
    // Now run the task
    // ----------------
    gulp.start('process');
    console.log(`\t\t\t\tprocessing ${subdirPath}`);
    cb();
};

// The main building task
// ----------------------
//      gets the parent directory
//      gets its top level subdirectories
//      asynchronously runs the actual processing task
//
gulp.task('build', () => {
    console.log('Hello world! Build me up!');

    // Get parent directory
    // --------------------
    let baseDir = process.env.baseDir || `${__dirname}/test`;
    baseDir = path.isAbsolute(baseDir) ? baseDir : path.join(__dirname, baseDir);

    console.log(`PARENT DIRECTORY = ${baseDir}`);

    // Asynchronously get the directory content
    // ----------------------------------------
    fs.readdir(baseDir, (err, items) => {

        // retrieve only top lever subdirectories
        //      use node-dir to get all nested directories
        let subdirs = _.filter(items, item => fs.statSync(`${baseDir}/${item}`).isDirectory());
        // get subdirectory full paths
        subdirs = _.map(subdirs, item => `${baseDir}/${item}` );

        console.log('PROCESSED SUBDIRS:');
        console.log(subdirs);

        // Asynchronously run the process task for each subdirectory
        // ---------------------------------------------------------
        //      async parameters:
        //          subdirs ...... array of subdirectories to work on
        //          subdirTask ... function variable, contains the work to be done
        //                              accepts two input parameters:
        //                                  1) subdirectory (provided implicitly by async)
        //                                  2) callback (provided as the third parameter to async.each)
        //          callback ..... callback function, the second parameter for subdirTask                         
        //          
        async.each(subdirs, subdirTask, (err) => {
            if (err) {
                console.error(err);
            } else {
                console.log(`Processing finished`);
            }
        });
        
    });
});

// default task is run when the gulp command is issued on its own
// --------------------------------------------------------------
gulp.task('default', ['build']);