Bower, a powerful browser package manager, allows you to manage your project assets, such as JavaScript, CSS, and images. In this post, we will focus on using Bower for JavaScript packages.
Before we begin, let’s install Bower using the npm package manager:
npm install bower -g
Next, create a .bowerrc file in your project’s root directory or in your home folder to customize Bower’s behavior. For example, you can specify the directory where packages will be installed and the file that will store Bower’s data:
{
"directory": "javascript/components",
"json": "bower.json"
}
The bower.json file, similar to the package.json file used in npm for Node.js packages, is responsible for managing assets.
Let’s start by adding a popular package to your project, such as jQuery:
bower install --save jquery
After installation, reference the package in your HTML code:
<script src="javascript/components/jquery/jquery.js"></script>
The --save
option tells Bower to add the package entry to the bower.json file, making it easy to recreate the same package structure later, similar to how npm manages packages in Node.js.
Updating to a newer jQuery release is simple:
bower update jquery
The Bower project maintains a list of popular packages, making it easy to install them. You can find a list of these packages ordered by popularity here.
Additionally, you can install any git-powered software using the git:// protocol or by specifying a URL:
bower install git://github.com/desandro/masonry
bower install http://foo.com/jquery.awesome-plugin.js
Bower is intelligent enough to install a specific tag or commit of a package. This allows you to install a previous version for compatibility or avoid upgrading to a newer package:
bower install git://github.com/components/jquery.git#~1.8.1
Uninstalling a package is as simple as:
bower uninstall jquery
I find Bower particularly useful when it comes to upgrading dependencies. Rather than searching through multiple GitHub projects, a simple bower update
command takes care of it. However, it’s still our responsibility to ensure that everything works correctly within our project.