【问题标题】:Better way to access a subtask in custom grunt task?在自定义 grunt 任务中访问子任务的更好方法?
【发布时间】:2023-04-03 08:00:01
【问题描述】:

我是 Grunt 的新手,我只构建了一些自定义的 grunt 任务。我将 initConfig 遍历到子任务的解决方案似乎非常不直观——我只是将一个正则表达式放在一起并使用一个开关来确定应该运行哪个子任务。有没有更好的方法到达这里?这是一个示例 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;
        }
    });
};

谢谢!

【问题讨论】:

  • 我以前研究过这个,除了在冒号上拆分:,我从来没有找到一个好的解决方案
  • @jakerella 即使这是朝着正确方向迈出的一步。谢谢!出于某种原因,我什至没有想过分手。尽管如此,API 中似乎应该有一些东西来避免这种需要。

标签: javascript node.js plugins gruntjs task


【解决方案1】:

在多任务中,“子任务”被称为目标。可通过this.target 访问。例如(取自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);
});

运行grunt log:foo 会写出foo: 1,2,3

因此,在您的代码中,您可以将 Regex 行替换为:

var subTask = this.target;

【讨论】:

    猜你喜欢
    • 2013-06-09
    • 2015-05-10
    • 1970-01-01
    • 2017-11-10
    • 2019-03-25
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    • 2016-03-22
    相关资源
    最近更新 更多