在Grunt任务中运行命令

Jua*_*anO 93 javascript continuous-integration templates google-closure-compiler gruntjs

我在我的项目中使用Grunt(基于任务的JavaScript项目命令行构建工具).我已经创建了一个自定义标记,我想知道是否可以在其中运行命令.

为了澄清,我正在尝试使用Closure模板,"任务"应该调用jar文件将Soy文件预编译为javascript文件.

我从命令行运行这个jar,但是我想把它设置为一个任务.

pap*_*boy 104

或者你可以加载grunt插件来帮助这个:

grunt-shell示例:

shell: {
  make_directory: {
    command: 'mkdir test'
  }
}
Run Code Online (Sandbox Code Playgroud)

或者grunt-exec示例:

exec: {
  remove_logs: {
    command: 'rm -f *.log'
  },
  list_files: {
    command: 'ls -l **',
    stdout: true
  },
  echo_grunt_version: {
    command: function(grunt) { return 'echo ' + grunt.version; },
    stdout: true
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 有谁知道这两个中的任何一个在Windows上是否可用? (9认同)
  • 对于简单的情况,两者在Windows下都可以正常使用. (7认同)
  • 有没有办法同步使用grunt-exec?将命令链接在一起会很好 (3认同)

Nic*_*ner 34

退房grunt.util.spawn:

grunt.util.spawn({
  cmd: 'rm',
  args: ['-rf', '/tmp'],
}, function done() {
  grunt.log.ok('/tmp deleted');
});
Run Code Online (Sandbox Code Playgroud)

  • 使用`opts:{stdio:'inherit'},`你可以看到命令的输出 (5认同)
  • 注意:cmd param应该是字符串而不是数组. (2认同)

Jua*_*anO 19

我找到了解决方案,所以我想与您分享.

我在节点下使用grunt所以,要调用终端命令,你需要'child_process'模块.

例如,

var myTerminal = require("child_process").exec,
    commandToBeExecuted = "sh myCommand.sh";

myTerminal(commandToBeExecuted, function(error, stdout, stderr) {
    if (!error) {
         //do something
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 更好的方法是使用插件(或编写自己的插件)将您的grunt配置保留为配置而不是代码.grunt-shell和grunt-exec就是两个例子. (12认同)

kik*_*ito 18

如果您使用的是最新的grunt版本(撰写本文时为0.4.0rc7),则grunt-exec和grunt-shell都会失败(它们似乎不会更新以处理最新的grunt).另一方面,child_process的exec是异步的,这是一个麻烦.

我最终使用了Jake Trent的解决方案,并将shelljs作为dev依赖项添加到我的项目中,因此我可以轻松地同步运行测试:

var shell = require('shelljs');

...

grunt.registerTask('jquery', "download jquery bundle", function() {
  shell.exec('wget http://jqueryui.com/download/jquery-ui-1.7.3.custom.zip');
});
Run Code Online (Sandbox Code Playgroud)


Art*_*pov 14

伙计们指的是child_process,但是尝试使用execSync来查看输出.

grunt.registerTask('test', '', function () {
        var exec = require('child_process').execSync;
        var result = exec("phpunit -c phpunit.xml", { encoding: 'utf8' });
        grunt.log.writeln(result);
});
Run Code Online (Sandbox Code Playgroud)