Reputation: 1581
I have Grunt build automation added in my project.
I have created one custom task which sets a variable for other task and now I want to run the task using the value I set.
grunt.registerTask('dist-flow', function () {
if (!grunt.option('env')) {
grunt.option('env', 'prod');
console.log(grunt.option('env'));
}
grunt.registerTask('dist',['dev_prod_switch']);
grunt.task.run('distdev');
});
But whenever I run the dist-flow
task it will set env
to prod
but dev_prod_switch
always take default value which I set for dev_prod_switch
.
So I want set the options from task and run specific task using that new value.
Upvotes: 0
Views: 934
Reputation: 60577
Based on your question and comments, I'm assuming your Gruntfile.js
looks something like this.
module.exports = function(grunt) {
grunt.initConfig({
dev_prod_switch: {
options: {
environment: grunt.option('env') || 'dev',
env_char: '#',
env_block_dev: 'env:dev',
env_block_prod: 'env:prod'
},
all: {
files: {
'appCommon/config.js': 'appCommon/config.js',
}
}
},
});
grunt.registerTask('dist-flow', function () {
if (!grunt.option('env') ) {
grunt.option('env', 'prod');
console.log(grunt.option('env'));
}
grunt.registerTask('dist',['dev_prod_switch']);
grunt.task.run('distdev');
});
};
Your issue is that you are trying to set the option
inside a task, and read it back in the initConfig
object. The trouble is, initConfig
runs before your tasks, so environment
has already been set to the default when your dist-flow
task is run.
environment: grunt.option('env') || 'dev',
grunt.option('env', 'prod');
Inside your task, you can access your config option through grunt.config
, so you could modify the value in the config object like so.
grunt.config.data.dev_prod_switch.options.environment = grunt.option('env');
module.exports = function(grunt) {
grunt.initConfig({
dev_prod_switch: {
options: {
environment: grunt.option('env') || 'dev',
env_char: '#',
env_block_dev: 'env:dev',
env_block_prod: 'env:prod'
},
all: {
files: {
'appCommon/config.js': 'appCommon/config.js',
}
}
},
});
grunt.registerTask('dist-flow', function () {
if (!grunt.option('env') ) {
grunt.option('env', 'prod');
console.log(grunt.option('env'));
grunt.config.data.dev_prod_switch.options.environment = grunt.option('env');
console.log(grunt.config.data.dev_prod_switch.options.environment);
}
grunt.registerTask('dist',['dev_prod_switch']);
grunt.task.run('distdev');
});
};
Upvotes: 4