Bower - Up and Running

How do you grab JavaScript files you need for a project? In the past I navigated to http://jquery.com and downloaded the latest minified and unminified version of jQuery. What if I need underscore? I would navigate to http://underscorejs.org and grab the latest version of underscore. Are your fingers cramped yet? I just want to grab some freakin JavaScript libraries! Thankfully, all of this low-level grunt work can be simplified greatly by using Bower.

I am going to assume you have Node and Npm already installed. If not jump to http://nodejs.org/ and download the installer there.

Install Bower globally using npm with the following command.

> npm install -g bower

You may need to use sudo. If the above command fails then try the following command.

> sudo npm install -g bower

Yay! We installed Bower! To illustrate how to use Bower we are going to make a folder called PixelBoy to hold the next great JavaScript web game. Navigate to the newly created folder.

> mkdir pixelboy
> cd pixelboy

Let's say we want to use jQuery and underscore in this project. Run the following commands.

> bower install jquery
> bower install underscore

After running those two commands you will have the following directory structure.

|-pixelboy
    |-bower_components
        |-jquery
            |- ...
        |-underscore
            |- ...

At this point you can statically reference jQuery via /bower_components/jquery/jquery.min.js in your script blocks in your html files. Here is an example script tag of how you could reference jQuery.

<script src="/bower_components/jquery/jquery.min.js"></script>

Nothing magical going on here. You are referencing a local javascript file. At this point you are both drunk with power as you can grab any JavaScript library with a twinkle of your fingers. You may also be disgusted by having bower_components hold your JavaScript files. The Bower folks have a built in mechanism to allow you to put the JavaScript files into any folder of your choosing.

Go to Your "Home" Directory... Bower

Why you don't you just go HOME? That's your HOME! Are you too good for your HOME? - Adam Sandler

Now you will see how to install the libraries to a directory of your choosing. Let's first get rid of the libraries we have already installed.

> bower uninstall jquery
> bower uninstall underscore

Create a new file called .bowerrc with the following contents.

{
    "directory": "scripts/vendor"
}

Run the install commands again.

> bower install jquery
> bower install underscore

The libraries were now installed into the scripts/vendor directory which is a more sensible installation directory.