His belief that clean, well-organized code is key to making software maintainable has led him to focus on unit testing and solid programming practices and principles as a cornerstone of everyday coding.
He is also the author of Require JS: Dependency Injection and Module Loading
Getting Started with Modules and Browserify
What Are Modules?
We learn that we’ll be refactoring a task list app in this course.
Modules encapsulate properties and functions, and are important for keeping your code clean.
Jeff explains the relationship between Browserify, Node JS and Common JS.
Defining and Requiring Modules
Setting up a Browserify Project
Covered here is installing Node JS and installing Browserify.
We’ll be creating 4 modules: app, tasks, taskRenderer and taskData.
Jeff starts by creating a taskData module. This contains three functions:
We use the exports to includes them in an exports object.
We see the equivalent module.exports code for what we just wrote.
Requiring 3rd Party Modules
Now we move onto the taskRenderer module. This module has two exported functions and one private function.
It also has a dependency on jQuery, and we can implement this easily:
var $ = require(‘jquery’);
Requiring Local Modules
We define the tasks module. Again this depends on jQuery.
The tasks module also depends on both our previously defined modules, and we learn that they are used with a relative path to them, e.g.
We must begin the paths with ./ otherwise browserify will look for an NPM installed module with the specified name.
Next we create app.js, which depends jquery and our tasks module. This contains only private functions: there is no need to export anything as it is the entry point of our application and no other module depend on it.
Jeff explains that Browserify takes all of the separate files and bundles them into a single file for us.
Modules Are Cached
Each module is only loaded once, then cached. This works in much the same way as Require JS.
We see there may be some situations where you don’t want singleton behaviour.
In these cases, you can new up another instance of your dependent module and by free to make modifications without affecting the original module.
Continue to Part 2 – Easing the Development Process