Accessing command line arguments with Grunt
4 years ago
I needed to be able to set up a watch task with Grunt to only watch a specific client sub directory. This directory would change depending on the client I was working on and new clients were constantly added so I need a way to watch the specific client that I was working on only, without hard coding all the clients into separate tasks. The only thing I could think of doing this was to pass some sort of parameters when starting the watch task.
This is how I set it up. It might not be the best method but it works for me.
First I had to set a value in the grunt configuration, which would be taken from the command line args. With Grunt you can get them them using:
You can also set a configuration value using:
So combining those two methods, the following will get a command line arg called “watchDir” (and assign a default value of src if it was not specified) and set it in the grunt config. I added this line after initConfig in my Gruntfile:
grunt.config.set('watchDir', grunt.option('watchDir') || 'src');
You can then access this property using a template string in your task:
files: ['clients/<%= watchDir %>/**/*.less'],
When running the Grunt task, we can specify the option “watchDir” by adding two dashes in front and setting it equal to the desired value:
grunt watch --watchDir="clientX"
The watch task above would in this case watch the following directory:
This allows you to set up a generic task that can be pointed to different directories when it is started.