user742030
user742030

Reputation:

gulp.src(globs) From a Variable Array

How can a variable (array) be used in gulp.src(globs)?

I have several Gulp tasks that use the same "group" of files but I do not know how to DRY the tasks to use the variable passed into the globs.

. . .
var configDir   = '../private/app/_config/',
    configFiles = [
        configDir + 'categories.yaml',
        configDir + 'params.yaml',
        configDir + 'taxonomies.yaml'
    ];

// Merge development config yaml(s)
gulp.task('yaml_merge-dev', function() {
  return gulp.src([
        'config.root.yaml',
        configDir + 'site.dev.yaml',
        configFiles
      ])
    .pipe(yamlMerge('config.dev.yaml'))
    .pipe(gulp.dest('../'));
});

// Merge production config yaml(s)
gulp.task('yaml_merge-prod', function() {
  return gulp.src([
        'config.root.yaml',
        configDir + 'site.prod.yaml',
        configFiles
      ])
    .pipe(yamlMerge('config.prod.yaml'))
    .pipe(gulp.dest('../'));
})
. . . // etc.

Upvotes: 1

Views: 1960

Answers (2)

Wilmer SH
Wilmer SH

Reputation: 1417

You are correct to want to DRY your tasks.

Using yargs, you can narrow down your code to a single task that uses command line arguments.

Run:

npm install --save-dev yargs

Javascript

. . . 
// Require yargs: https://www.npmjs.com/package/yargs
var args = require('yargs').argv;

// Site file based on argument
var siteFile = args.release? 'site.prod.yaml' : 'site.dev.yaml';

// Merge config file based on argument
var yamlMergeConfig = args.release? 'config.prod.yaml' : 'config.dev.yaml';

// Single declatations for readibility
var configDir = '../private/app/_config/';

// Your config files in a single glob
var configFiles = [
        configDir + 'categories.yaml',
        configDir + 'params.yaml',
        configDir + 'taxonomies.yaml'
        configDir + siteFile
    ];

gulp.task('yaml_merge', function() {
  /// <summary>
  /// Merge development or production config yaml(s)
  /// gulp yaml_merge             : deploys the development build
  /// gulp yaml_merge --release   : deploys the release build
  /// </summary>
  return gulp.src(configFiles)
    .pipe(yamlMerge(yamlMergeConfig))
    .pipe(gulp.dest('../'));
});
. . . // etc.

Upvotes: 1

Sven Schoenung
Sven Schoenung

Reputation: 30564

gulp.src() only accepts one flat array of files, not nested arrays. That means you have to add all the files in configFiles to the array that you pass to gulp.src().

Since gulp is just JavaScript, you can use any of the many possible ways that you can combine arrays in JavaScript. In your case Array.prototype.concat() is probably the most appropriate:

gulp.task('yaml_merge-dev', function() {
  return gulp.src([
    'config.root.yaml',
    configDir + 'site.dev.yaml'
  ].concat(configFiles))
  .pipe(yamlMerge('config.dev.yaml'))
  .pipe(gulp.dest('../'));
});

Upvotes: 1

Related Questions