Grunt this.files适用于非多任务

时间:2014-01-16 14:12:41

标签: javascript gruntjs

在Gruntjs中定义多任务时,我能够做到

grunt.registerMultiTask("taskName", "taskDescription", function () {
  this.files.forEach(function (mapping) {
    // mapping.src and mapping.dest are defined here,
    // no matter which format was used to configure files in the task
  });
});

执行this.files时,为什么grunt.registerTask无效?或者是这样的情况我不允许在任务配置中使用不同的文件格式,而不是多任务(紧凑格式,对象格式,数组格式,定义here)?

当不在多任务中时,访问src和目标文件映射的最简单方法是什么?我想做

grunt.initConfig({
  my_task: {
    // I don't want to define a target here
    files: {
      // I want to be able to use any format here
      "my/target/folder": "my/src/files/*"
    }
}

grunt.registerTask("my_task", "description", function () {
  this.files // ==> undefined
});

1 个答案:

答案 0 :(得分:1)

根据Grunts API,您必须使用参数运行任务,以便能够在taskFunction回调中获取任何参数。

如果您运行grunt foo,您将获得foo, no args,如果您运行grunt foo:testing:123,则会生成foo, testing 123

grunt.registerTask('foo', 'A sample task that logs stuff.', function(arg1, arg2) {
  if (arguments.length === 0) {
    grunt.log.writeln(this.name + ", no args");
  } else {
    grunt.log.writeln(this.name + ", " + arg1 + " " + arg2);
  }
});

grunt.registerTask函数this回调上下文中的taskFunction对象会给你这个..

{ nameArgs: 'foo',
  name: 'foo',
  args: [],
  flags: {},
  async: [Function],
  errorCount: [Getter],
  requires: [Function],
  requiresConfig: [Function],
  options: [Function] }

虽然这是grunt.registerMultiTask函数的上下文taskFunction回调会给你这个..

{ nameArgs: 'my_task:files',
  name: 'my_task',
  args: [],
  flags: {},
  async: [Function],
  errorCount: [Getter],
  requires: [Function],
  requiresConfig: [Function],
  options: [Function],
  data: { thefile: 'thesource' },
  files: [],
  filesSrc: [Getter],
  target: 'files' }

要回答您的问题,files任务中的my_task对象无法在您需要的上下文中访问。