使用api运行grunt任务,无需命令行
问题描述:
我想在node.js代码中创建并运行grunt任务以供测试使用。
I want to create and run grunt task in node.js code for test use.
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*/]);
}
但这不起作用。 Grunt似乎没有运行任何任务。我几乎可以肯定,有一些API可以在没有命令行的情况下在外部运行grunt任务,但不知道该怎么做。
But this doesn't work. Grunt doesn't seem to run any task. I'm almost sure that there is some API to run grunt task externally without command line, but don't know how to do it.
有什么办法可以做它是什么?
Is there any way to do it?
答
你可以。我不知道为什么有人需要这样做,因为目前Grunt是一个命令行工具。 警告:我不建议以这种方式运行Grunt。但是,它是:
You can. I don't know why anyone would need to do this as currently Grunt is a command line tool. WARNING: I don't recommend running Grunt in this way. But here it is:
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.');
});