定义自定义 Grunt 任务并将它们与其他任务链接起来

Defining custom Grunt tasks and chain them with others

我有以下 Gruntfile.js:

module.exports = function(grunt) {
  var config = {
    shell: {
      ...
    },
    copy: {
      ...
    }
  };
  grunt.initConfig(config);

  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-shell');

  grunt.registerTask('default', ['shell:compile', 'copy:jsfiles']);
};

我正在使用 grunt-contrib-x 组件,这些组件可以配置,然后作为链的一部分在任务中注册。

自定义任务呢?

我需要添加另一个由函数执行的任务:

var customTask = function() {
  // This will do something...
};

我需要 运行 它在 shell:compilecopy:jsfiles 之后作为另一个任务的一部分,并且也在其他链中。我想要相同的模式并能够做类似的事情:

module.exports = function(grunt) {
  var config = {
    shell: { ... }, copy: { ... },
    customTask: function() {
      // Doing stuff
    }
  };
  // ... some code ...
  grunt.registerTask('default', ['shell:compile', 'copy:jsfiles']);
  grunt.registerTask('advanced', ['shell:compile', 'copy:jsfiles', 'customTask']);
  grunt.registerTask('advanced2', ['shell:compileComponent', 'copy:jsfilesComponent', 'customTask']);
};

目标是可以创建任务链并将我的自定义任务作为要执行的顺序任务列表的一部分。

我怎样才能做到这一点?

调用 grunt.registerTask 并将名称作为第一个参数传递,将函数传递给 运行 作为最后一个参数。

grunt.registerTask('myTask', function () {
  //do some stuff
});

然后你可以链接它

grunt.registerTask('advanced', ['shell:compile', 'copy:jsfiles', 'myTask']);

基本上它与您的示例相同,只是您将自定义任务定义为 grunt.registerTask 的参数,而不是配置中的 属性。

http://gruntjs.com/creating-tasks#custom-tasks