A module is an organizational unit of code, and usually represents code designed to do one task, or one function. If you store like-purposed code in its own bundle, you will always know where to come looking for it when bugs come up in the future.
Modules are used in order to:
- Encourage single responsibility for code units
- Improve code maintainability / organization
- Namespace code so there are no collisions between modules
Modularity is a useful tool to create clean code, and thus modules can be found in most languages.
An improvement that allows private methods and properties is the following:
This method makes use of an instantaneously invoked function expression. (iife). Note however that this module is incapable of having a parent that establishes the module’s default functionality. Extensibility is easily added like so:
In order to load asynchronously and resolve dependencies that don’t exist yet, the following pattern is required:
AMD requires the specification of module dependencies in an iife like above using the keyword define();
CommonJS uses the following syntax to establish a module:
The file name is what is required by client code using this invocation:
Each file therefore forms its own module capable of its own namespace. For server-side code such a system is sensible, but when a browser requests multiple scripts that must then be returned separately, long delays may result. To solve this, Browserify pre-compiles all dependencies into one file which can then be returned to the client efficiently.
The require method here can be replicated by the following function: