Sunday, January 31, 2016

javascript decomposition with bower's shorthand resolver


We started using bower to manage third party dependencies in our projects, and realized that we could also use bower to help decompose our javascript applications into re-usable independently tested components. We started out with a lazy approach where we setup a jscommon/ folder under which we installed our different components (jscommon/A/, jscommon/B/, jscommon/C/, ...) where each component might have its own build and test scripts - whatever it needs.

We started out representing dependencies between components with file URL's in bower.json files, so if C depended on B and A, then it might have a bower.json file like this:

  {
     ...
     "dependencies" : {
            "A" : "../A",
            "B" : "../B"
     }
   }

Of course - that quickly falls apart when an application's bower.json file has a different relative path to the jscommon/ folder, but using a shorthand resolver solves the problem. An application (or test or whatever) registers a shorthand resolver in a .bowerrc file with the appropriate relative path like this:

{
    ...
    "shorthand-resolver" : "../../{{shorthand}}"
}

, and we specify local dependencies in bower.json with short-hands like this:

  {
     ...
     "dependencies" : {
            "A" : "jscommon/A",
            "B" : "jscommon/B"
     }
   }

No comments: