One of the problems that I have often run in to with building re-usable components in an application, is the ugly require statements that I have to use:
The deeper the folder structure, the worse it gets! So how do we get rid of this ugliness?
Reduce The Ugly
My goal is to reduce require statements shown above, into a simple statement like this:
This is a problem I’ve already tackled in my node apps and I want to solve it for my browser based modules with Browserify, too.
But, I Don’t Wanna NPM It!
At first glance, I thought my only option was to publish a module into NPM. While this is a valid option, it’s not one that I want to do most of the time.
Typically, when I’m building a component within my application, it is for this application only. I don’t want other people to see it, and I don’t want other applications that I’m building to see it, either.
I know I could use private NPM modules for this, but doesn’t really fit either. My components for an application are only for that application.
And I Don’t Want node_modules, Either
There are other options for having NPM “install” a module in to the node_modules folder, by pointing at a file system… but this presents another problem of semantics. In this case, I’m writing code that is strictly for the front-end browser. This isn’t node code, nor is it unimorphic isoversal JavaScrode.
I don’t want my front-end components in my node_modules folder because they don’t belong there. I want my front-end components in a folder structure that is organized for my front-end code.
Browserify’s “paths” To The Rescue
Fortunately for my sanity and my code, I found my answer in the “paths” setting of Browserify. I was able to adjust my Grunt file to include this settings, like this:
With Browserify pointed at the “common” folder of my application, I can place a named sub-folder with an index.js file in that sub-folder, and include the component in my app easily!
Now, instead of using using all those ugly “../../../common/whatever” relative paths, I can just
require("myComponent"); and I’m done.