用api运行grunt任务,不用命令行

我想在node.js代码中创build并运行grunt任务以供testing使用。

var foo = function() { var grunt = require("grunt"); var options = {"blahblah": null} // ...creating dynamic grunt options, such as concat and jshint grunt.initConfig(options); grunt.registerTask('default', [/*grunt subtasks*/]); } 

但是这不起作用。 咕噜似乎没有运行任何任务。 我几乎可以肯定,有一些API可以在没有命令行的情况下在外部运行grunt任务,但不知道如何去做。

有没有办法做到这一点?

您可以。 我不知道为什么有人需要这样做,因为目前Grunt是一个命令行工具警告:我不build议以这种方式运行Grunt。 但这里是:

 var grunt = require('grunt'); // hack to avoid loading a Gruntfile // You can skip this and just use a Gruntfile instead grunt.task.init = function() {}; // Init config grunt.initConfig({ jshint: { all: ['index.js'] } }); // Register your own tasks grunt.registerTask('mytask', function() { grunt.log.write('Ran my task.'); }); // Load tasks from npm grunt.loadNpmTasks('grunt-contrib-jshint'); // Finally run the tasks, with options and a callback when we're done grunt.tasks(['mytask', 'jshint'], {}, function() { grunt.log.ok('Done running tasks.'); }); 

你可以从grunt-cli中得到灵感,这个grunt-cli是这样做的,哪一个是由咕噜咕噜的人维护的项目。

Grunt是从grunt-cli / bin / grunt中的代码启动的,你可以阅读更多关于grunt / lib / grunt / cli.js中的选项 。

我在这样一个私人项目中使用它:

 var grunt = require("grunt"); grunt.cli({ gruntfile: __dirname + "/path/to/someGruntfile.js", extra: {key: "value"} }); 

grunt.option("extra")可以在gruntfile里面使用“extra”这个关键字

这里是一个bloggpost,描述了一个运行咕噜任务的替代方法: http ://andrewduthie.com/2014/01/14/running-grunt-tasks-without-grunt-cli/