ForGach in Grunt任务配置

JQu*_*ile 3 gruntjs

我正在研究Gruntfile配置.我需要遍历所有匹配模板变量中定义的模式的文件,如下所示:

module.exports = {
    templates: {
        all: ['src/templates/**/*.html*’]
    }
};
Run Code Online (Sandbox Code Playgroud)

我需要将这些文件中的每一个用作此处定义的'swapper'目标上名为'files'的数组中的值:

task-config :{
  swapper : {
    files: { 
      // foreach (file in templates) {
      //   ‘destination/‘ + “‘“ + file.ToString() + “‘“ : ‘file.ToString()’
      //   if (isNotLastFile()) {
      //      appendComma()
      //   }
      // }
   },
   tasks: ['jshint:ignore_warning:test' ],
     options: {
       encodeSpecialChars: true
     }
  }
}
Run Code Online (Sandbox Code Playgroud)

我很难让语法正确.甚至可以做我在Grunt尝试的事情吗?或者,我需要以不同的方式去做吗?

谢谢

Kyl*_*ung 5

IIFEs对此非常有用(尽管有些人认为,Gruntfiles是javascript并使用Node.js编写):

"task-config": {
  swapper : {
    files: (function() {
      var templates = require('./templates.js').templates;
      var out = {};
      Object.keys(templates).forEach(function(key) {
        var val = templates[key];
        // Do something with key/val to determine the dest/src
        var dest = 'destination/' + someHowDetermineYourDestination(val);
        out[dest] = val;
      });
      // Return the computed object
      return out;
    }())
  },
},
Run Code Online (Sandbox Code Playgroud)

有关IIFE的更多信息,请查看此文章:http://benalman.com/news/2010/11/immediately-invoked-function-expression/

你可能不需要IIFE.而只是使用expand选项:

"task-config": {
  swapper : {
    expand: true,
    cwd: 'src/templates/',
    src: ['**/*.html'],
    dest: 'destination/',
  },
},
Run Code Online (Sandbox Code Playgroud)

这将在每个文件内src/templates输出和输出任务,包括文件夹的子文件destination/夹.

有关详细信息,请参阅Grunt文档的此部分:http://gruntjs.com/configuring-tasks#building-the-files-object-dynamically