Irishka
Irishka

Reputation: 1136

gruntjs: use files with dynamic mapping in multitask config once for all targets

in my multi task I want to use dynamic mappings for files config property

files: [
    {
      expand: true,     // Enable dynamic expansion.
      cwd: 'lib/',      // Src matches are relative to this path.
      src: ['**/*.js'], // Actual pattern(s) to match.
      dest: 'build/',   // Destination path prefix.
    },
  ] 

is it possible to specify the "files" property once for all targets (and they would be expanded) to avoid redundancy? all targets are working with the same file structure, with the same files

something like:

taskName: {
  target1: { prop1:1 },
  target2: { prop1:2 },
  files: [
    {
      expand: true,     // Enable dynamic expansion.
      cwd: 'li...
      ...
    }
  ]
} 

I can write files inside 'options' property, but then I need to call expand functions on that files manually.

Thank you

[EDIT]

for testing:

grunt.registerMultiTask('taskname', 'im looking for files', function () {
  grunt.log.writeflags(this.files, 'this.files');
  console.log('this.files'.yellow, this.files); //double check ;)
});

Upvotes: 3

Views: 1547

Answers (2)

Irishka
Irishka

Reputation: 1136

the solution, I've found, is to use grunt.file.expandMapping method to programmatically generate a files array

grunt.config

'taskname': {
    target1: { prop1:1 },
    target2: { prop1:2 },

    options: {
      defProperty: "defValue",
      dFiles: { //default files object
        cwd: 'lib/',      // Src matches are relative to this path.
        src: ['**/*.js'], // Actual pattern(s) to match.
        dest: 'build/'   // Destination path prefix.
        //any other property if you need (e.g. flatten, ext)
      }
}

taskname.js

grunt.registerMultiTask('taskname', 'im looking for files', function () {

    var curTask = this,
        opts = curTask.options();

    if (!curTask.files.length && 'dFiles' in opts) {
      var df = opts.dFiles;

      curTask.files = grunt.file.expandMapping(df.src, df.dest , df);
    }

    console.log('this.files: '.yellow, this.files);

});

Upvotes: 1

asgoth
asgoth

Reputation: 35829

Just store the files property in a variable and use that where you need it:

var myFiles = [
    {
      expand: true,     // Enable dynamic expansion.
      cwd: 'lib/',      // Src matches are relative to this path.
      src: ['**/*.js'], // Actual pattern(s) to match.
      dest: 'build/',   // Destination path prefix.
    }
  ]; 


taskName: {
  target1: { 
     prop1:1,
     files: myFiles
  },
  target2: { 
     prop1:2,
     files: myFiles
  }
} 

If this is still too much, you could do it completely via javascript by changing the config:

var tasknameConfig = grunt.config('taskname');
var target;

for (target in tasknameConfig) {
  tasknameConfig[target].files = myFiles;
}
grunt.config('taskname', tasknameConfig);

Upvotes: 0

Related Questions