94

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

为了澄清,我正在尝试使用闭包模板,“任务”应该调用 jar 文件将 Soy 文件预编译为 javascript 文件。

我正在从命令行运行这个 jar,但我想将它设置为一个任务。

4

6 回答 6

106

或者,您可以加载 grunt 插件来帮助解决这个问题:

咕噜壳示例:

shell: {
  make_directory: {
    command: 'mkdir test'
  }
}

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
  }
}
于 2012-11-01T23:07:38.100 回答
36

签出grunt.util.spawn

grunt.util.spawn({
  cmd: 'rm',
  args: ['-rf', '/tmp'],
}, function done() {
  grunt.log.ok('/tmp deleted');
});
于 2013-02-13T21:23:46.350 回答
20

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

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

例如,

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

myTerminal(commandToBeExecuted, function(error, stdout, stderr) {
    if (!error) {
         //do something
    }
});
于 2012-05-07T19:25:16.197 回答
18

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

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

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');
});
于 2013-02-03T20:00:41.030 回答
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);
});
于 2015-04-22T14:18:17.357 回答
2

对于使用 Grunt 0.4.x 的异步 shell 命令,请使用https://github.com/rma4ok/grunt-bg-shell

于 2013-03-10T23:10:48.173 回答