I spent a lot of this week trying to understand npm and bower, the differences between them, and how to implement them. I just could not grasp the usefulness of either, when to use each one, or which one is considered better.
How can searching their package lists be any easier than searching for the libraries’ websites on Google or their files on a CDN?
Why are there so many package managers that do the same thing?
Why can’t I find a blog post or Stack Overflow answer that just tells me what I should use?
At the end of the week, I have no additional features to show for it, but I finally believe I grasp the two primary solutions for front-end dependency management. And since I couldn’t find a decent writeup anywhere, I decided I should make one that would have helped me.
Recursive bacronymic abbreviation for “npm is not an acronym”
There’s a lot of misinformation about npm on the Internet. Contrary to what many people think, npm is not just for Node packages. It’s a very good package manager, and it’s what you use to install bower itself.
To use npm modules in the browser, you will need a tool like browserify or webpack. You can include and manipulate the downloaded files in
node_modules yourself if you wish, but doing so is contrary to npm’s modular nature, and isn’t recommended.
The primary technical difference between the two package managers is their handling of dependencies. Npm’s module dependencies are saved in a tree. If
module A depends on
module C@1.0.0 and
module B depends on
module C@2.0.0, both versions of
module C will be installed and
B will each use their own copies. This can take a lot of space, but it is safer and an overall better method.
The package manager for the web
Unlike npm, bower was designed specifically for the browser. It does one simple thing and does it pretty well: download files. It doesn’t do anything particularly special, it downloads what you tell it to along with any dependencies, and you do whatever you want with them.
Because web browsers operate in a flat dependency model, so does bower. If multiple versions of a package are installed, it just asks which you want to use. Using the previous example, when bower detects that
B both depend on
C of different versions, it will ask you which you want to use, and both
B will use the version you selected. This can be problematic and packages
B might not behave properly, but it’s a simple way to appeal to browsers’ flat nature.
Until this point, I had been using CDNs to include the libraries I was using. I spent several hours refactoring my code to work well with browserify before I decided it wasn’t worth it and decided on bower.
If still don’t know which you want to use