Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically set options for grunt task?

I have a grunt task that looks at options with grunt.option('foo'). If I'm calling this task from grunt.task.run('my-task'), how can I change those arguments?

I'm looking for something like:

grunt.task.run('my-task', {foo: 'bar'});

which would be the equivalent of:

$ grunt my-task --foo 'bar'

Is this possible?

(This question is another issue I ran in to but is not exactly the same, because in this case I don't have access to the original task's Gruntfile.js.)

like image 448
Nick Heiner Avatar asked Feb 13 '13 21:02

Nick Heiner


5 Answers

If you can use task-based config options instead of grunt.option, this should work to give you more granular control:

grunt.config.set('task.options.foo', 'bar');
like image 167
jjt Avatar answered Sep 20 '22 07:09

jjt


Looks like I can use the following:

grunt.option('foo', 'bar');
grunt.task.run('my-task');

It feels a bit odd to set the options globally instead of just for that command, but it works.

like image 35
Nick Heiner Avatar answered Sep 19 '22 07:09

Nick Heiner


Create a new task which set the option, then call the modified task. This is a real life example with assemble:

grunt.registerTask('build_prod', 'Build with production options', function () {
  grunt.config.set('assemble.options.production', true);
  grunt.task.run('build');
});
like image 27
Alessandro Pezzato Avatar answered Sep 20 '22 07:09

Alessandro Pezzato


In addition to @Alessandro Pezzato

Gruntfile.js:

grunt.registerTask('build', ['clean:dist', 'assemble', 'compass:dist', 'cssmin', 'copy:main']);

    grunt.registerTask('build-prod', 'Build with production options', function () {
        grunt.config.set('assemble.options.production', true);
        grunt.task.run('build');
    });

    grunt.registerTask('build-live', 'Build with production options', function () {
        grunt.option('assemble.options.production', false);
        grunt.task.run('build');
    });

Now you can run

$ grunt build-prod

-OR-

$ grunt build-live

They will both do the full task 'build' and respectively pass a value to one of the options of assemble, namely production 'true' or 'false'.


In addition to illustrate the assemble example a bit more:

In assemble you have the option to add a {{#if production}}do this on production{{else}}do this not non production{{/if}}

like image 26
Remi Avatar answered Sep 22 '22 07:09

Remi


grunt is all programmatic.. so if you have set options on tasks before, you have done this programmatically.

just use grunt.initConfig({ ... }) to set options for tasks.

and if you already initialized, and need to change configuration afterwards, you can do something like

grunt.config.data.my_plugin.goal.options = {};

I am using it for my project and it works.

like image 39
guy mograbi Avatar answered Sep 21 '22 07:09

guy mograbi