gruntjs:对多个目标使用多任务配置中的动态映射文件

时间:2013-04-10 13:34:05

标签: gruntjs

在我的多任务中我想为文件配置属性

使用动态映射
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.
    },
  ] 

是否可以为所有目标指定一次“files”属性(并且它们会被扩展)以避免冗余? 所有目标都使用相同的文件结构,具有相同的文件

类似的东西:

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

我可以在'options'属性中写文件,但是我需要手动调用这些文件的扩展函数。

谢谢

[编辑]

进行测试:

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

2 个答案:

答案 0 :(得分:1)

我发现,解决方案是使用 grunt.file.expandMapping 方法以编程方式生成文件数组

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);

});

答案 1 :(得分:0)

只需将files属性存储在变量中,然后在需要的地方使用该属性:

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
  }
} 

如果这仍然太多,你可以通过更改配置完全通过javascript完成:

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

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