Share javascript in node and the browser with Browserify

Posted by: Seth Lakowske

Published:

My goal is to use one language across two environments, the server and the browser. I want to do so easily and I have attempted to achieve this in the past, but ran into difficulties.

Requirejs:

I tried Requirejs on the server and browser. I thought the API was unnatural relative to CommonJS, but if it got me to my goal of shared Javascript, I would accept it as a cost of commonality. Additional cost crept in, I started managing a Requirejs configuration script, which started simple, but became more unweildy as I "shimed" various libraries that I wanted to require in my project. Some libraries didn't shim right, befuddled I spent hours searching google for how to get library X to work with Requirejs. I didn't like spending time debugging my tools. This was supposed to be easy.

Browserify:

My initial exposure to Browserify was while I was writing a Backbone application and testing with Mocha and Sinon. These libraries were not written as CommonJS modules - the native module system of Nodejs. As a consequence, there was no guarantee they would work well with Browserify. At the time, I was more concerned with these libraries than my module system, so I choose to go with Requirejs. While the pains of Requirejs started to build, I kept reading about people using Browserify. I was also becoming more familiar with Nodejs and its pipe API, which I am fond of from my Unix experience. When I learned the power of pipes and streams was available in the browser via Browserify, I decided to give Browserify another try.

So far, Browserify is working well - it lets me use the pipe API I love in Nodejs. Other Nodejs modules are available also. When I write a new module, I can write it in typical Nodejs fashion and I feel comfortable knowing it will work in the browser and Nodejs. I switched my unit test library from Karma to Tape. Tape is written by substack, the same person who created Browserify, so of course it works with Browserify. I finally feel like I have a tool that allows me to write code for nodejs and the browser. Most importantly, it is easy to use and comprehend. I haven't had to put much thought into shared code in a while, which is exactly how I like it!