I’ve recently started building out our projects with the well known module pattern and a tool called Browserify. I made this architectural decision because I wanted a way to manage dependencies and at the same time limit our impact on the global scope. Browserify uses CommonJS modules as its pattern. This appealed to me because it is the same pattern that Node JS uses.
Browsers don’t have the require method defined, but Node.js does. With Browserify you can write code that uses require in the same way that you would use it in Node.
The traditional module pattern looks like this:
This pattern allows us to contain our module into logical pieces of functionality without falling into creating mega objects with many properties and methods which encourages the overuse of the this keyword. Private and public functions are clearly stated and easy to read.
Additionally, the module is wrapped in an Immediately Invoked Function Expression (IIFE) which prevents the global scope from being polluted. Todd Motto has written a good article explaining the benefits of the pattern.
This line tells other files in our application to include it as a dependency. Previously you would have to make sure that the script from exampleModule.js was loaded or defined before using it in another module.
Then if we wanted to use our exampleModule in another file. We’d include it with this line:
The piece that brings everything together is what’s called an endpoint in browserify. The endpoint is the script that browserify compiles and combines all the references into a large bundled file.
Consider this folder structure:
Inside of our endpoint called app.js we would have the following:
There are lots of options to then bundle your Browserify files. I prefer to use gulp, but you can also do it with the command line.
Adding new dependencies to a project is done via the package.json. The name of the package and the version are all controlled via the npm package manager and then bundled with Browserify. This works in the following way.
To include a new dependency you would type this while in your project’s working directory
npm will then download jquery into your node_modules folder. If you look at the previous code example you’ll see this line
This isn’t a relative path because Browserify knows to look in the package.json for dependencies. So, if it doesn’t find a an index.js or the name of the file you’ve specified it’ll search the node_modules for the appropriate file. The global object tells Browserify that you’d like to include jQuery in ALL of your files which then releases you from writing var $ = require(‘jquery’); in all of your files.
Feel free to tweet me @iamdaninphilly about anything I may have gotten wrong, I’m always open for discussion!
- A simplified application folder structure.
- Built in dependency management.
- Less pollution in the global scope.
- No broken references