Running grunt task with api, without command line

前端 未结 2 1555
不知归路
不知归路 2020-12-25 08:00

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\"         


        
相关标签:
2条回答
  • 2020-12-25 08:37

    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.');
    });
    
    0 讨论(0)
  • 2020-12-25 08:55

    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/

    0 讨论(0)
提交回复
热议问题