简体   繁体   English

在自定义grunt任务中访问子任务的更好方法?

[英]Better way to access a subtask in custom grunt task?

I'm new to Grunt and I've only built a few custom grunt tasks. 我是Grunt的新手,我只构建了一些自定义的grunt任务。 My solution for traversing the initConfig to subtasks seems pretty unintuitive--I just threw a regex together and used a switch to figure out which subtask should be running. 我将initConfig遍历到子任务的解决方案似乎很不直观-我只是将正则表达式放在一起,并使用开关来确定应该运行哪个子任务。 Is there a better way of getting here? 有没有更好的方法来这里? Here's a sample Gruntfile: 这是一个示例Gruntfile:

module.exports = function(grunt) {
    grunt.initConfig({
        myTask: {
            add:{
               //files object, options etc
            },
            remove:{
               //files object, options etc                
            }
        }
    });
    grunt.registerMultiTask('myTask', 'A sample task with a regex and switch for subtasks', function() {
        var subTask = this.nameArgs.match(/.*?:(.*?):/)[1];
        switch(subTask){
            case "add":
                //code for task "add"
                break;
            case "remove":
                //code for task "remove"
                break;
        }
    });
};

Thanks! 谢谢!

In a multitask, the "subtask" is known as a target. 在多任务中,“子任务”被称为目标。 It's accessible via this.target . 可通过this.target访问。 For example (taken from http://gruntjs.com/api/grunt.task#grunt.task.registermultitask ): 例如(取自http://gruntjs.com/api/grunt.task#grunt.task.registermultitask ):

grunt.initConfig({
  log: {
    foo: [1, 2, 3],
    bar: 'hello world',
    baz: false
  }
});

grunt.task.registerMultiTask('log', 'Log stuff.', function() {
  grunt.log.writeln(this.target + ': ' + this.data);
});

Running grunt log:foo would write out foo: 1,2,3 . 运行grunt log:foo将写出foo: 1,2,3

So in your code, you could replace the Regex line with: 因此,在您的代码中,您可以将Regex行替换为:

var subTask = this.target;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM