CommonJS functionality is implemented in the Curl Library As pointed out in other answers RequireJS
follows the AMD spec which is different than Node's CommonJS var foo = require('foo');
spec.
Curl Features at a glance:
- Loads AMD-formatted javascript modules in parallel
- Loads CommonJS/node modules (v1.1 when wrapped in a define())
- Loads CommonJS/node modules (unwrapped when using the cjsm11 loader)
- Loads non-AMD javascript files in parallel, too.
- Loads CSS files and text files in parallel
- Waits for dependencies (js, css, text, etc) before executing javascript
- Waits for domReady, if desired
- Allows for virtually limitless combinations of files and dependencies
- Tested with Safari 5+, IE6+, and recent Chrome, FF, Opera
Browserify does not implement CommonJS straight out but rather transpiles your CommonJS style code into a single bundle.js
file which is included in the html.
Webmake seems to offer similar functionality to Browserify while also allowing for other file types.
In a nutshell CommonJS works like this:
- Maintain a map of identifiers that correspond to loaded modules.
- When a
require('lib')
is encountered, check the list to see if it has been loaded. If the library has not been loaded (it's key is not in the library), load the script via XHRRequest. If the library has been loaded, return the value that corresponds to the key
.
This is why required modules are always singletons.