Running grunt task with api, without command line

萝らか妹 提交于 2019-12-18 10:54:23

问题


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*/]);
}

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?


回答1:


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.');
});



回答2:


You can get inspiration on how to run grunt from code by looking at grunt-cli which does this and which is a project maintained by the grunt folks.

Grunt is launched from code in grunt-cli/bin/grunt and you can read more about the options in grunt/lib/grunt/cli.js.

I use it in a private project like this:

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

The key "extra" will be available from inside the gruntfile as grunt.option("extra")

Here is a bloggpost that describes an alternative way to run a grunt task: http://andrewduthie.com/2014/01/14/running-grunt-tasks-without-grunt-cli/



来源:https://stackoverflow.com/questions/16564064/running-grunt-task-with-api-without-command-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!