在一个Gruntfile中运行另一个Grunt任务

23

我在项目根目录下有一个Gruntfile。 我还通过Bower在app/components/jquery目录中安装了jQuery。

作为我的Gruntfile的一部分,我想对jQuery Gruntfile运行一些命令以构建自定义版本库。

我如何从我的Gruntfile访问其Gruntfile?

4个回答

29

您可以创建一个简单的任务,在您想要的文件夹中生成grunt

grunt.registerTask('run-grunt', function () {
    var done = this.async();
    grunt.util.spawn({
        grunt: true,
        args: [''],
        opts: {
            cwd: 'app/components/jquery'
        }
    }, function (err, result, code) {
        done();
    });
});

2
这几乎奏效了…但是需要什么来展示任务输出呢?比方说我有一个任务 karma:unit,它使用 watch:true 运行我的单元测试。我想要能够运行它并在屏幕上看到输出。 - pgpb.padilla
如果您想要实时查看它,您将需要启动自己的子进程 https://nodejs.org/api/child_process.html 并响应数据事件 - 否则只需将结果输出到控制台 console.log(result.stdout); - moefinley

16

如果你想要获得控制台输出,可以基于 @Sindre 的回答,只需要在代码中使用 console.log 输出 result.stdout 即可。

grunt.registerTask('run-grunt', function() {
    var cb = this.async();
    grunt.util.spawn({
        grunt: true,
        args: ['clean', 'copy:fonts'],
        opts: {
            cwd: 'bower_components/bootstrap'
        }
    }, function(error, result, code) {
        console.log(result.stdout);
        cb();
    });
});

1
完美运行,当然输出是缓冲的。 - Lee Goddard

11

根据 @Sindre 和 @Stephen 的回答,我们也可以实时获取控制台输出而不被缓冲:

grunt.registerTask('run-grunt', function() {
  var cb = this.async();
  var child = grunt.util.spawn({
      grunt: true,
      args: ['clean', 'copy:fonts'],
      opts: {
          cwd: 'bower_components/bootstrap'
      }
  }, function(error, result, code) {
      cb();
  });

  child.stdout.pipe(process.stdout);
  child.stderr.pipe(process.stderr);
});

运行良好,也适用于Visual Studio任务运行器资源管理器。 现在我可以通过项目根目录中的gruntfile来运行Bootstrap gruntfile中的任务(这对于任务运行器资源管理器是必需的)。 - ArieKanarie

0

不确定是否可行,但你可以尝试一下。你的jQuery Gruntfile通过“module.exports”进行导出。这应该意味着你可以在你的代码中require它并使用它。

var jQueryGrunt = require('path-to-jquery-gruntfile');
jQueryGrunt.task.run(['your-task-you-want-to-run']);

很有趣听到那是否有效...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接