Reputation: 24791
In my Gruntfile I have pieces of config which are initialised after analyzing some external information.
Those dynamic parts of config are needed only by specific tasks, and, since generating them is not completely cheap operation.
My question is - what is the best way to change/add grunt config just before some specific task is called.
What I've tried so far. My first attempt was based on following idea:
module.exports = function(grunt) {
grunt.initConfig({
log: {foo: 'This should be overridden'}
});
grunt.task.registerMultiTask('log', 'Log stuff.', function() {
grunt.config.set('log.foo', 'log.foo overriden!');
grunt.log.writeln(this.target + ': ' + this.data);
});
grunt.registerTask('default', 'log');
};
This failed, but give me a hint on how to make a working decision:
module.exports = function(grunt) {
grunt.initConfig({
log: {foo: 'This should be overridden'}
});
grunt.task.registerTask('logWrapper', 'Log stuff.', function() {
grunt.config.set('log.foo', 'log.foo overriden!');
grunt.task.run('log');
});
grunt.task.registerMultiTask('log', 'Log stuff.', function() {
grunt.log.writeln(this.target + ': ' + this.data);
});
grunt.registerTask('default', 'logWrapper');
};
Though this works, but looks overcomplicated and a quite impractical.
Upvotes: 2
Views: 188
Reputation: 24791
OK, this is exactly this extremely rare case when I feel I've found the better solution than that that've been provided here.
We can use getters:
module.exports = function(grunt) {
grunt.initConfig({
get log() {
grunt.log.writeln('Dynamic config');
return {
foo: 'This will be called only when log task is called'
}
}
});
grunt.task.registerMultiTask('log', 'Log stuff.', function() {
grunt.log.writeln(this.target + ': ' + this.data);
});
grunt.task.registerTask('dummy', 'Just a dummy task', function() {
grunt.log.writeln('Hey! I\'m dummy!');
});
};
grunt log
will trigger log evaluation, while grunt dummy
won't.
Upvotes: 0
Reputation: 6069
grunt.option can be a clean way to handle dynamic tasks.
Give log
a template with a grunt option in it:
log: "<%= grunt.option('log') || {foo: \'This should be overridden\'} %>'
and override in a wrapper or other task with grunt.option('log', {foo: 'newvalue'})
.
Upvotes: 1
Reputation: 13725
You can do it this way as well:
grunt.task.registerTask('logWrapper', 'Log stuff.', function() {
grunt.config.set('log.foo', 'log.foo overriden!');
});
grunt.registerTask('default', ['logWrapper','log']);
Otherwise these pages can be useful:
Upvotes: 2