Robert T
Robert T

Reputation: 233

How to pass a variable to a task in gulp.parallel

I have a gulp series which contains lines such as:

gulp.parallel( compressCSS1, compressCSS2, minifyHTML1, minifyHTML2 )

But compressCSS1 and compressCSS2 are really the same function, just operating on different files, such as:

function compressCSS1() {
return gulp.src( filesExist("./folder1/*.css", existOptions), {base: './'} )
    .pipe( debug() )
    .pipe( csso() )
    .pipe( gulp.dest( './', {overwrite:true} ) );
}

So I basically end up with a bunch of nearly identical functions, which I would of course prefer to avoid.

Is there a way I could instead rewrite that function to generically specify accept a different glob? The answer for me is not a different glob, as there are a variety of scenarios I run into where that won't work (in some cases the input may be different options for another set of files, etc).

I'm instead trying to figure out how to pass a variable to a function within a Gulp task. In other words, something idealogically like:

gulp.parallel( compressCSS(arg1), compressCSS(arg2), minifyHTML(arg3), minifyHTML(arg4) )

Thank you for any help with this!

Upvotes: 1

Views: 579

Answers (1)

nottherealironman
nottherealironman

Reputation: 389

If your end goal is to avoid repeating the same minifying script, then you could create a function that takes two arguments:

  • List of files which needs to be minified
  • Name of the output file

The skeleton of function could be like this:

function compressCSS(assets, filename) {
  return gulp.src(assets)
    .pipe( debug() )
    .pipe( csso() )
    .pipe(concat(filename)) // Name of the output file
    .pipe( gulp.dest( './', {overwrite:true} ) );
}

Then, you could call the generic function as below from main function.

async function compressAllCSS() {
    compressCSS('./folder1/*.css', 'main.min.css');
    compressCSS('./folder2/*.css', 'header.min.css');
}

NOTE: Don't omit the async keyword here. It allows the function calls inside this function to be called asynchronously.

Finally, you can call the main function from the gulp task as below:

gulp.parallel(compressAllCSS, minifyHTML)

Upvotes: 1

Related Questions