Accessing command line arguments with Grunt
7 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:
1 | grunt.option('someCommandLineArg'); |
You can also set a configuration value using:
1 | grunt.config.set('myValue', 'someValue'); |
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:
1 | grunt.config.set('watchDir', grunt.option('watchDir') || 'src'); |
You can then access this property using a template string in your task:
1 2 3 4 5 6 | watch: { less: { files: ['clients/<%= watchDir %>/**/*.less'], tasks: ['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:
1 | grunt watch --watchDir="clientX" |
The watch task above would in this case watch the following directory:
1 | 'clients/clientX/**/*.less' |
This allows you to set up a generic task that can be pointed to different directories when it is started.
Author: Ben Foster Date: September 23, 2014