I have grunt configured in an Angular project and it's a hassle to have to run it every time I want to generate new files.
Is there a way to make it run automatically whenever I make a change to one?
Thank you
I have grunt configured in an Angular project and it's a hassle to have to run it every time I want to generate new files.
Is there a way to make it run automatically whenever I make a change to one?
Thank you
This task can be accomplished using the watch package.
1. INSTALL WATCH
You can install it with:
2. DEFINE WATCH IN GRUNT
Once installed, we define a watch object defined inside the
Gruntfile.js
:In this example, I'm watching all the .js files in the folders:
As soon as it detects a change, it will run the task you want . In my example it runs the uglify task.
3. RUN TASK
In the previous point we told grunt to run the uglify task . In case you're curious, the definition is this:
What this particular uglify task does is unify all the js files into a single file called
ejemplo.js
You can install uglify with
4. ACCESS THE package.json
In options you can see that it makes use of a variable called
pkg.name
, this is the name of my application defined in thepackage.json
. You can read thepackage.json
from grunt with this definition:5. DECLARE PACKAGES IN GRUNT
Finally, remember that you have to declare the npm packages in
Gruntfile.js
so grunt can load and access them:6. Bonus track: Default task
You can define a default task in grunt like this:
Now when executing via terminal
The task will be executed
uglify
7. RUN WATCH IN THE BACKGROUND
Finally we will leave it running
watch
in the background so that each new change made in the files.js
mentioned above executes the defined task. We are going to execute the following command:Note: The
&
will allow us to continue executing commands in the terminal. If you prefer to leave that terminal only for watch then rungrunt watch
8. End result
The file
Gruntfile.js
is like this:With grunt-contrib-watch you can make the grunt tasks run when a change is detected in the files or folders you decide.
It has good documentation and there are many examples on the Internet.
I hope I've helped!