Home Web Development Learning Grunt

Learning Grunt

By Douglas Reynolds
books-svg-icon Book
eBook $25.99 $17.99
Print $32.99 $18.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $25.99 $17.99
Print $32.99 $18.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
About this book
With the increasing focus on task automation, the Grunt task runner is a vast platform that allows you to incorporate automation into your workflows. At the outset, you will learn how to use Node.js and NMP through an example. You will then find out how to build a sample app and the development environment for it. You will further delve into the implementation of Grunt plugins and the configuration of Grunt tasks. Furthermore, you will explore the various methods and packages for workflow automation. The final chapter will cover some advanced concepts, such as configuration variables and how to create a Grunt plugin. By the end of the book, you will have gained the fundamentals of Grunt and progressed through advanced concepts, including building a Grunt plugin.
Publication date:
March 2016
Publisher
Packt
Pages
184
ISBN
9781785888809

 

Chapter 1. Grunt Dependencies

Grunt is a JavaScript task runner. As its name alludes, this tool performs the grunt work of completing development tasks, which might include linting JavaScript, running tests, generating minified JavaScript and CSS, moving files and directories, creating archives, and the list goes on and on. In fact, the purpose of Grunt is task automation, which means running one or more tasks with the least amount of user interaction needed in order to complete the work. Almost any task can be automated with Grunt and many plugins (tasks) already exist that can be installed and used in your project. It is possible to write and publish your own plugins to meet the need of tasks for which a plugin does not already exist. You can also modify existing plugins to meet project-specific requirements. The Grunt community is very large and there is a great deal of documentation and resources available as a result. With a minimum amount of research effort, information on specific Grunt topics can be found in a wide range of places. This book, for one, will provide information on the installation and setup of Grunt, installation and configuration of tasks found in the Node Package Manager (NPM) registry, creation of custom tasks, Grunt API documentation, and much more. Some main benefits of using the Grunt task runner are that Grunt task automation improves productivity by handling repetitive tasks with efficiency, reduces errors using automated processes, and lessens the workload so that less time and energy is spent on things that can be handled through workflow automation. Once the upfront work of Grunt implementation has been completed, there is practically no additional work needed to run tasks. It is a very simple matter to create custom task runners for various build stages of projects with fine-grained control over what tasks get run for various stages. For instance, it is possible to create a custom task that includes error checking and syntax validation, running a suite of unit tests, and then, upon success, building the project to a development release version and generating a deployment archive. The possibilities for various build configurations are vast. However, first things first, there are some things that need to be discussed prior to diving in.

 

Dependencies


Before jumping into Grunt.js, you first need to understand that Grunt has some dependencies that are needed in order to get up and running with task automation. In this case, the dependencies are Node.js and Node Package Manager (NPM). While a deep level of Node.js knowledge is not a prerequisite to using Grunt.js, a high-level understanding of Node.js and NPM is needed to get started.

Node.js and NPM are required for the installation of the Grunt command line interface (CLI) as well as plugins that are used for task automation in Grunt. We will get into plugins later in the book, so don't be too concerned with what exactly a plugin is at this point. Suffice it to say that a plugin is a script that performs a certain task in Grunt. These tasks can be run individually or as a series of tasks that run as part of what is called a custom task. Some examples of common tasks are as follows:

  • JSHint: JSHint runs JavaScript validation (lint). This runs code that analyzes JavaScript for errors or syntax that has the potential to be a bug.

  • Uglify: This task minifies files by removing all excess characters from code without changing or breaking the functionality of the code.

  • LESS: This is a task that compiles LESS files into CSS files.

  • Watch: This responds to additions, changes, and deletions of files by running preconfigured tasks, for instance, if you wish to build your project or run lint on files every time the file is changed and saved.

An example usage scenario, using these tasks listed, might be to run JSHint to lint JavaScript source files. If errors exist, the task halts and provides message(s) related to the errors and warnings found. If no errors exist, then the task completes and the Uglify task is run to minify the JavaScript source files, outputting them to the distribution directory. Next, the LESS task is run to generate and output CSS to the distribution directory. Finally, the Watch task is run so that it will continue to monitor changes to files when they occur. Watch might start the entire build process again without any user interaction. This is really powerful and frees up the developer who would otherwise need to perform each task manually every time files were changed.

There are many official plugins such as these that have been created and are maintained by the Grunt team. Official plugins are prefixed with contrib-, so the naming of plugins listed previously would be found as contrib-jshint, contrib-uglify, contrib-less, and contrib-watch as each one of these plugins is officially maintained by the Grunt team.

There are unofficial plugins created and contributed to the project by other organizations and developers as well. Examples of common unofficial plugins include the following:

  • concurrent: This runs tasks concurrently

  • newer: This runs tasks on source files that have changed

  • open: This opens URLs and files from a task

  • notify: This provides automatic desktop notifications for errors and warnings

What has been listed here isn't even the tip of the iceberg of the plugins available to add to your project for workflow automation. You might find that you are spending time on a task that is repetitive and error prone. What if you could write a script that would perform this task for you and ensure that it is done correctly every time? Well, with Grunt, you can create your own plugins and even contribute them to the NPM registry so that others who have the same need can benefit.

Now that we have a bit of introduction of what Grunt can do, let's discuss more about the Node.js and NPM dependencies. In the following sections, we will get to know some introductory information about Node.js and NPM. We will look at procedures for the installation of Node, which will include upgrade processes as well as pristine installations on both Mac and Windows. The Grunt Command Line Interface will be introduced; this is where we will actually begin working with Grunt tooling:

  • An overview of Node.js and NPM

  • Upgrading or installing Node.js

  • Using NPM to manage the Grunt CLI

Grunt.js and Grunt plugins require Node.js and NPM in order to be installed. As a result, Node.js and NPM are dependencies of Grunt. Node.js is the server environment in which Grunt will run. NPM is the package manager that will be used to install plugins from the NPM repository. NPM will make it easy to install code written by other developers who have shared their solutions so that others, such as us, can benefit from reuse.

In order to go further into details about Node.js and NPM, the following questions will be answered in this section:

  • What is Node.js and NPM?

  • Where can I find Node.js and NPM?

What is Node.js and NPM?

Node.js is a runtime environment that uses the Google V8 engine to execute JavaScript on your machine, be it OS X, Windows, Linux, or SunOS (at the time of writing). There are also some unofficial builds for other platforms provided by members of the community. If you use the Google Chrome web browser, then you are using an application built with the Google V8 engine. Google V8 implements ECMAScript and is an open source project. If you have not heard of ECMAScript prior to this book, ECMAScript is a language standards specification. Some well-known languages, which are varying degrees of implementation of ECMAScript, are JavaScript, Microsoft's jScript, and Adobe's ActionScript. By varying degrees, it is to be understood that a language such as JavaScript is not ECMAScript; rather, the JavaScript core implementation is based on ECMAScript, yet JavaScript implements features that are in addition to ECMAScript.

So, what is Node? The Node.js platform is an asynchronous event-driven framework, which allows developers to create network applications (for example, HTTP or SMTP). Node allows developers to create applications running on a host that can be accessed by clients on another host, for instance, a web browser accessing a website or an e-mail application requesting mail on a mail server. This is by no means the limit of the functionality of Node.js. Applications can be built to run on the Node.js environment, which do not require client/server architecture between separate hosts. In fact, Grunt.js is an example of an application that runs on Node.js within the same host environment. The Node.js environment makes it possible to write JavaScript programs that are not reliant on browser interpretation. Node.js allows developers to write JavaScript applications that run as server-side applications.

Node.js provides a package manager that we will use to install Grunt, aptly named Node Package Manager (NPM). NPM provides access to scripts and applications in the NPM registry along with the ability to manage these applications on the user's machine for installation and updates as well as some additional features such as publishing packages. Grunt and Grunt plugins require NPM to be installed because they are managed with NPM. A package manager is an application that provides a utility for developers to share and provide updates to their plugins, which, in turn, end users can use in order to install, configure, update, and remove these applications from their machines. NPM will provide you with just such a utility needed for Grunt and Grunt plugins. We will use NPM regularly to install and possibly update packages while we set up and configure Grunt in our application in order to provide task automation.

Where can I find Node.js and NPM?

Node.js is an open source project that is maintained by individuals who collaborate and help steer future development efforts of the platform:

All of the documentation and information about Node.js can be found on the Node.js organization website, https://www.nodejs.org/. Node.js isn't a brand new technology, yet it isn't that old either; Node.js' first release, v0.0.1, on GitHub was on May 27, 2009. Applications intended to run on the Node.js platform are written in JavaScript, allowing developers to leverage the expressiveness of JavaScript outside of the browser in a server-side environment.

NPM used to be a separately maintained project from Node.js, so in previous versions of Node.js, NPM was obtained through a separate installation. NPM is now provided as part of the Node.js core installation; when you install Node.js, you will have NPM without any further installation requirements. All that you will need to do is proceed to the downloads page on the Node.js site, https://nodejs.org/download/, choose the prebuilt installer for your platform, and download it on your machine. We will go over the upgraded and pristine installation of Node.js for both Mac and Windows in the next sections.

 

Upgrading or installing Node.js


In this section, we will go through the process of the Node.js installation. As of the time of writing this, the current version of Node.js is v4.3.1. Some readers may already be up and running with Node; for others, this may be the first introduction to the server platform. As a result, we will cover the steps necessary for both an upgrade and a new installation:

  • Upgrading Node.js via NPM on Mac

  • Upgrading Node.js via .msi and NPM

  • The pristine installation of Node.js via a downloaded binary

  • Adding your installation path to your $PATH variable

If you do not have Node.js installed on your machine, feel free to jump to the "Pristine Installation of Node.js via downloaded binary" section. If you have a previous version of Node installed, know that Grunt requires Node versions greater than or equal to 0.8.0. If you want to upgrade, it is strongly recommended that you perform a backup prior to performing the Node.js upgrade process. For those on Mac, continue reading the next section. For those of you on Windows, feel free to jump to the Upgrading Node.js via .msi and NPM section.

Upgrading Node.js via NPM on Mac

Upgrading Node.js via NPM is very straightforward and shows you just how great a utility NPM is. We will use a Terminal application in order to update Node from the command-line interface. This process assumes that you have an existing instance of Node.js installed globally. If you do not have Node.js installed as a global application, you will need to change directories to the location where Node.js is installed and perform the update from this location. A global installation of Node.js provides an entry to your PATH variable and you will be able to access it via the command line from any directory. A local installation might be in a project root where you are using specific Node.js versions in a project.

It is important to note that the upgrade process uses a Node binary manager module called n. The n module is not maintained by Node.js. Therefore, proceed with caution and at your own risk when performing the upgrade process that follows. Information on the n module can be found at its GitHub page, https://github.com/tj/n. It is strongly suggested that you review the project's documentation prior to proceeding with an upgrade. Additionally, make sure that you have a recent backup.

With this said, I have used the following upgrade process many times without the slightest issue. I am extremely confident in using the n module to upgrade my own Node.js versions.

To get started, first check for the current version of Node that is installed on your machine:

$ node --version

You can also use another command showed as follows:

$ node –v

This will display the currently installed version of node. Your result may differ but should look something like the following version, which was the output from calling the version command:

v0.10.29

The next line deletes the contents of the NPM cache so that we can ensure that we are not working with stale files/data. The sudo requests administrator privilege, npm defines the application to be used, cache manipulates the packages cache, and clean deletes the data from the cache directory. Depending on your user, you may need to include a super user prefix, such as sudo, in order to have permissions to perform the following commands. If you get an error message that alludes to permissions, then your user does not have sufficient privilege and the use of super user prefix or logging in as administrator user will be needed. Syntax using sudo is provided as it doesn't hurt anything to include it in the commands; however, it may not be necessary, depending on whether your installation exists globally or locally:

$ sudo npm cache clean -f

If you are using sudo and are not currently logged in as an administrator, you will be prompted for your password in the next line. If you are not using sudo, then this step will be omitted:

$ password:

Enter your password and press ENTER to continue.

You may now be presented with an NPM warning that notifies you that NPM is using force. This is seen because of the -f flag used in the command that was issued previously:

$ npm WARN using --force I sure hope you know what you are doing.

Continue with the installation. In the following line, I am using the sudo administrator to run the npm application in order to install the n application globally by using -g. I will use the n module to upgrade Node.js:

$ sudo npm install -g n

As n is installed, I will see some path information displayed, which shows where n has been installed. When this is complete, I am ready to upgrade node with the following command. The sudo administrator will use the n application to install the latest stable version of Node.js:

$ sudo n stable

The command runs n with the stable option. This will get the latest stable version of Node.js from the server. You can also request a specific version by replacing stable with the version string that you wish to install, for example, sudo n 0.12.7.

At this point, you should see a result similar to the following, which confirms the version being installed along with the path information. In this case, the result is that node-v0.12.7 was installed in a new directory located in /usr/local/n/versions/node/0.12.7. Confirmation of the installed version shows v0.12.7. Your version may differ significantly, so don't be alarmed by the version number represented here:

install : node-v0.12.7
       mkdir : /usr/local/n/versions/node/0.12.7
       fetch : https://nodejs.org/dist/v0.12.7/node-v0.12.7-darwin-x64.tar.gz
   installed : v0.12.7

The entire Terminal series of commands should resemble the following screenshot. If, by chance, your node version was already up to date, n will not provide any output, as shown in the following screenshot:

At this point, you have either successfully upgraded Node.js or discovered that your version of Node.js is up to date. In either case, you are now prepared to move forward to add your installation path to your $PATH variable.

Congratulations! You have updated Node.js.

Be sure to have a look at the n GitHub pages for other useful commands, such as 'rm' to remove Node.js. If you have multiple versions of Node.js installed, you can specify, similar to the installation, the version that you want to remove using the rm command.

Upgrading Node.js on Windows via .msi and NPM

For those of you that currently have Node installed on Windows, the process of upgrading is basically the same as that of a new installation. The simplest approach is to use the Node Windows Installer, .msi, available from the Node.js downloads page, https://nodejs.org/download/:

Prior to beginning, check your current version of Node so that you can verify that you have successfully updated Node and NPM when the installation process was completed:

$ node –version

You can also use another command shown as follows:

$ node –v

Your expected output should be the version of Node that is currently installed on your machine:

v0.10.29

Choose the Windows Installer .msi file that is appropriate for your machine and download it. Once the download is completed, run the installer file to begin the Node.js installation. Follow the prompts to run the installation, accept the terms of the license agreement, and continue completing the installation.

The final step of the Windows upgrade process is to update all of the existing global packages. This will require cleaning of the package cache and then performing an update of all global packages. We can do this in two lines with the following commands:

npm cache clean
npm update -g

You have successfully upgraded Node.js or discovered that your version of Node.js is up to date. At this point, you are now prepared to move forward to add your installation path to your $PATH variable.

Congratulations, you have successfully updated Node.js!

The pristine installation of Node.js via downloaded binary

For those of you who do not have a version of Node.js installed yet, the following steps for the installation are for you. The examples illustrated here are from the Mac installer; while the Windows installer will be a little different, the installation process is basically the same. For this installation, we will download the binary installation file and install it on your machine. The current version as of the writing of this book is 4.3.1. Navigate to https://nodejs.org/download/ to find the available downloads for various platforms:

Choose the correct download link for your platform. For the purposes of this book, we will use a binary installer (.exe for Windows or .pkg for Mac) and will not be building Node.js from source. The examples that follow will be for the Mac platform. If you are installing in Windows, simply follow the steps outlined in the installer application.

After downloading the binary, run the installer file to open the installation dialogue. The first view that we are presented with is the Introduction. Note the line defining the installation path. Click on Continue to proceed to review and accept the license agreement:

Click on Continue, and once you have reviewed the agreement, then Agree to the license that is presented in the pop-up window that is launched:

Select the Install for all users of this computer option to enable the Continue button in order to proceed:

Press Install in order to accept the default location shown in step 1 of the installation:

Node.js will be installed in the default, or specified, directory. You will then be presented with the summary view of the installation:

Congratulations, you have successfully updated Node.js!

Verify that your install location for node is on your path by checking for node's version from the Terminal command line:

$ node –version

If you receive an error resembling the following, then the installation path needs to be added to your $PATH variable:

-bash: node: command not found

The next section will cover how to add the installation path to your $PATH variable.

Adding your installation path to your $PATH variable

For Windows 7, the process of editing the Path variable is as follows:

  1. Choose Properties from the My Computer context menu (right-click).

  2. Choose the Advanced tab from the System Properties window.

  3. Click on the Environment Variables button in the Advanced section of the window.

  4. Select the Path item from the list of variables and click on the Edit button.

  5. Append the path where node was installed to the Path variable; they are separated by semicolons.

  6. Choose OK to save the changes to Path:

For Mac OS X, we will edit the $PATH variable from within Terminal using the Nano editor. You can use vi editor as well for the same purpose. It is even possible to use Text Edit.

To begin, let's first check our existing $PATH variable value by echoing the path variable in Terminal:

$ echo $PATH

You should see a result with the current value of your $PATH variable, the following for example:

$ /usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin

Next, change directories to the home directory using the Change Directory (cd) command:

$ cd

Create a .bash_profile file if it does not exist, or open the .bash_profile file in nano for the editing. This file exists at the root of your user directory:

$ nano .bash_profile

If you prefer to use Text Edit, you can use the open command with [-e], which instructs the command to use Text Edit:

open -e .bash_profile

You can use [-a] in the command to define the specific application to open the file by defining a named application:

open -a TextEdit .bash_profile

You should see the contents of your .bash_profile file in the nano editor. It will be empty if you have never created one before. In the following example, I have already defined locations to be included in my path. As you can see, my .bash_profile already exists and has content in it:

Add the following line to the file, where [PATH_TO_NODE_INSTALL_DIRECTORY] is the path where the Node installer application installed Node.js:

PATH=$PATH:[PATH_TO_NODE_INSTALL_DIRECTORY]

Save the file in nano by pressing Ctrl + O and confirm that the filename is to be saved as .bash_profile by hitting return. Exit nano by pressing Ctrl + X.

You can exit terminal and reopen in order to start a new terminal session and allow the changes to take effect; however, an even better way is to enter the following command to reload your .bash_profile:

$ source .bash_profile

In this method, there is no need to restart the Terminal application; the source command executes the file defined as the argument—in this case, .bash_profile—thus the $PATH variable has been updated.

Using NPM to install the Grunt Command Line Interface

Up until this point, we have been working on installing the dependencies of Grunt. Now, we finally get to start working on the installation of the Grunt CLI. Installing the Grunt CLI is the first step in the process of setting up automated tasks with Grunt and we will use the CLI for all of our grunt work. While this was a pun and not that funny, the CLI has one specific purpose: to be able to run the grunt command from anywhere on your system. This is why we will be installing the CLI globally, which means that it will be able to run from any location, globally, on your machine.

 

Installing the Grunt CLI


NPM is used to install Grunt and the Grunt CLI. The process of installation is very simple. As we just completed the updating or installing of Node, it should not be necessary to update NPM. If it has been a while since you updated NPM, now would be a good time to do so. Updating NPM is very simple and straightforward.

Updating NPM

Updating NPM is performed in one line. We will use the [sudo] administrator to run the [npm] application in order to [update] the [npm] application globally [-g]:

sudo npm update -g npm

That's right! We use NPM to update itself! The sudo npm command specifies that we want to run NPM as an administrator, the -g flag denotes a global update, and the ensuing npm specifies that NPM is the application that we are updating. This is the basic syntax for all NPM commands.

Installing Grunt CLI

The Grunt CLI is the first thing that we need to install as the Grunt CLI's sole responsibility is to run Grunt, as mentioned in the previous section. When we issue the install command, we will be placing the grunt command to the global path so that it is available from within all of your projects. Acting as the [sudo] administrator, we will run [npm] in order to [install] the [grunt-cli] globally [-g]:

sudo npm install -g grunt-cli

It is important to point out that we are not installing Grunt at this point. As mentioned, the primary purpose of the CLI is to run Grunt. Perhaps this sounds a bit confusing at the moment, but don't overthink it. What this means is that we will be installing Grunt within each project using the Grunt CLI. As a result, this will provide a means for us to maintain control over Grunt versions associated with projects. For example, say the current version of Grunt at the time you started a project was v0.4.3. You would be able to install this Grunt version in your project without affecting any other project-specific implementation of Grunt. Later, in case you begin a new project and the current version is v0.4.5, you will be able to install this version in your new project without affecting the project with v0.4.3 implemented. If you wish, you could update your first project from v0.4.3 to v0.4.5. This results in your ability to upgrade Grunt within a project as you see fit without affecting any instance of Grunt being used for other projects. When you run Grunt from the CLI, it will be associated with a local version of a Grunt configuration file, known as a gruntfile. Grunt can be run from any directory in your project.

If you try to run Grunt from outside of your project directory, in a location where Grunt has not been installed with the Grunt CLI, you will receive an error such as the following:

grunt-cli: The grunt command line interface. (v0.1.13)
Fatal error: Unable to find local grunt.

If you're seeing this message, either a Gruntfile wasn't found or Grunt hasn't been installed locally to your project. For more information about installing and configuring Grunt, please see the Getting Started guide:

http://gruntjs.com/getting-started

In this case, you will need to either install Grunt in the location that you expected it to be or change directories to the location where Grunt is actually installed.

 

Summary


Grunt is a JavaScript task runner whose purpose is task automation. Using automation, developers can find benefits through improved productivity, error reduction, and reduced workload of mundane tasks. You learned that Grunt has some dependencies that need to be installed before we can begin using Grunt in our projects. Grunt requires that Node.js and the NPM be installed so that we can install the Grunt CLI, which we will use to install Grunt. It wasn't necessary to get too deep into the understanding of Node.js and NPM at this point; we only needed to have a high-level understanding of the technologies in order to help us get the Grunt CLI up and running.

Some plugins were mentioned, such as contrib-watch, contrib-jshint, and contrib-uglify, that will be used later to illustrate task configuration to automate our workflows. As you perform your daily development activities, perhaps you can identify the repetition of certain tasks. Imagine being able to automate these tasks; with Grunt, you could write your own plugin to do just this. You could even share it with others by contributing it as an unofficial Grunt plugin.

The next chapter will cover the creation of an application that will be used for examples throughout the remainder of this book. This will involve using an application scaffold, which will generate an AngularJS application. This will allow the rapid setting up of the environment needed to write, build, and run the Grunt automated tasks that will be covered in later chapters.

About the Author
  • Douglas Reynolds

    Douglas Reynolds is a web application developer. He holds a degree in software engineering and has worked with web technologies for over 15 years. Douglas currently works for Herff Jones as a Senior Web Applications Developer as a member of a highly skilled and dedicated team of professionals. Douglas writes and lectures on web technologies, teaches at Illinois State University in the Department of Technology, and writes on topics of technology for Packt Publishing. Douglas and his wife of over 20 years, along with their son and two dogs, live in Bloomington, Illinois. He loves his family and friends and enjoys spending time outdoors in nature, riding his Harley, and continually developing his relationship with God.

    Browse publications by this author