Bower Installer

October 13, 2014

I like bower. It certainly is not perfect, but it beats the alternative. I just recently discovered bower-installer. This takes bower to the next level. Bower, out of the box, will essentially just download your dependencies and throw them into a directory. It is still up to you to determine which files among those downloaded that you need to include in your application. Bower installer adds an additional step which does ‘installation’.

I am using bower installer for this very blog. There are a few steps involved which I walk walk through.

Step 1: define your bower dependencies

Create a bower.json file that contains your bower dependencies:

{
    "name": "mattjmorrison.com",
    "dependencies": {
        "ember": "1.7.0"
    }
}

Step 2: install bower-installer and your bower dependencies

Create a package.json file that looks something like this:

{
    "name": "mattjmorrison.com",
    "dependencies": {
        "bower-installer": "*"
    },
    "scripts": {
        "postinstall": "bower-installer"
    }
}

Then running npm install will install bower-installer as well as your bower dependencies.

At this point bower has done the normal process of just downloading everything. After running npm install there will be a directory called bower_components that looks something like this:

bower_components
 |-- ember
 |    +-- ( all ember files here )
 |-- handlebars
 |    +-- ( all handlebars files here )
 +-- jquery
      +-- ( all jquery files here )

Step 3: ‘Install’ the bower dependencies, rather than just download

The next step involves us modifying our bower.json file to tell it where to install the files.

{
    "name": "mattjmorrison.com",
    "dependencies": {
        "ember": "1.7.0"
    },
    "install": {
        "path": {
            "js": "assets/js/lib/",
        }
    }
}

With this new configuration it will take the main script defined in each bower dependeny’s bower.json file and install it to the path specified in your bower.json file. With this configuration you will still have a bower_components directory (which should be ignored by source control) but you will also get an assets/js/lib directry which should just be the files that you need. In my scenario it looks something like this:

assets
 +-- js
      +-- lib
           |-- ember
           |    +-- ember.js
           |-- handlebars
           |    +-- handlebars.js
           +-- jquery
                +-- jquery.js

This is much better than just having a huge dump of all of the files that come along with each of those frameworks. In my scenario for this blog I have my assets directory under source control. I can easily update my dependency versions by running npm install again after updating the versions that I need in bower.json.

The roots of education are bitter, but the fruit is sweet. - Aristotle