Web Modules
Problems
- Web sites are turning into Web apps
- Code complexity grows as the site gets bigger
- Developer wants discrete JS files/modules
Solution
- Some sort of
#include/import/require
- Ability to load nested dependencies
CommonJS
The dominant incarnation of this specification is Node.js
modules (Node.js
modules have a few features that go beyond CJS).
Characteristics:
- Compact syntax
- Designed for synchronous loading
- Main use: server
Basic example
AMD - Asynchronous Module Definition
AMD specification is implemented by Dojo Toolkit, RequireJS etc.
Basic exmaple
Conditional loading example
Issues
For the project of medium complexity, HTTP overheads for asynchronous downloading of single Javascript files are dramatic. Therefore, RequireJS
advises developers to proceed with a bundling operation of the various modules using their command line tool.
Bundling process
The process parses the files begining at a specified entry-point to reconstruct the dependencies on the basis of the define()
calls that it finds along the way. It is then able to organize and concatenate all of the necessary files in a single file i.e. bundle.js
which we will then be included in our HTML.
UMD - Universal Module Definition
Since CommonJS and AMD styles have both been equally popular. This has brought about the push for a universal pattern that supports both styles.
The pattern is both AMD and CommonJS compatible, as well as supporting the old-style global variable definition.
Browserify
Unlike RequireJS
, Browserify
allows you to write your client-side application making use of CommonJS
’s synchronous loading (using Node.js
). How is this possible?
- Bundling similar to require.js
browserify app.js --outfile bundle.js
The content of every module, including the entry-point, can be requested during runtime by being passed to debundle()
which implements the module.exports/require
- CommonJS
mechanism on the client side.