|
1 | 1 |
|
2 | | -# CommonJS Module System |
| 2 | +# CommonJS Module System |
| 3 | + |
| 4 | +[CommonJS](http://commonjs.org) is a community driven effort to standardize packaging of JavaScript libraries, known as _modules_. Ideally modules written in JavaScript which support the CommonJS module pattern can be re-used within many environments such as node, narwhal, and even browsers among others. |
| 5 | + |
| 6 | +## Creating Modules |
| 7 | + |
| 8 | +Lets create a utility module named _utilities_, which will contain a `merge()` function to copy the properties of one object to another. Typically in a browser, or environment without CommonJS module support, this may look similar to below, where `utils` is a global variable. Although namespacing can lower the chance of collisions, it can still become an issue, and when further namespacing is applied it can look flat-out silly. |
| 9 | + |
| 10 | + var utilities = {}; |
| 11 | + utilities.merge = function(obj, other) {}; |
| 12 | + |
| 13 | +CommonJS modules remove this conflict by "wrapping" the contents of a JavaScript file with a closure similar to what is shown below, however more pseudo globals are available to the module, not just `exports` and `module`. The `exports` object is then returned when a user invokes `require('utils')`. |
| 14 | + |
| 15 | + var module = { exports: {}}; |
| 16 | + (function(module, exports){ |
| 17 | + exports.merge = function(){}; |
| 18 | + })(module, module.exports); |
| 19 | + |
| 20 | +First create the file _./utilities.js_, and define the `merge()` function below. |
| 21 | + |
| 22 | + exports.merge = function(obj, other) { |
| 23 | + var keys = Object.keys(other); |
| 24 | + for (var i = 0, len = keys.length; i < len; ++i) { |
| 25 | + var key = keys[i]; |
| 26 | + obj[key] = other[key]; |
| 27 | + } |
| 28 | + return obj; |
| 29 | + }; |
| 30 | + |
| 31 | +Next we will look at utilizing out new module in other libraries. |
| 32 | + |
| 33 | +## Requiring Modules |
| 34 | + |
| 35 | +Create a second file named _./app.js_ with the code shown below. First we load in the core `sys` module, which provides common methods such as `sys.puts()`, `sys.print()`, and the object inspection method `sys.p()`. |
| 36 | + |
| 37 | + |
| 38 | + var sys = require('sys'), |
| 39 | + utils = require('./utilities'); |
| 40 | + |
| 41 | + var a = { one: 1 }; |
| 42 | + var b = { two: 2 }; |
| 43 | + utils.merge(a, b); |
| 44 | + sys.p(a); |
| 45 | + |
| 46 | +Since the `sys` module is bundled with node, it's `exports` are returned, however for other modules node will iterate the `require.paths` array in search of a module matching the given path. By default `require.paths` includes _~/.node_libraries_, so if we have _~/.node_libraries_/utilities.js_ we may simply `require('utilities')`, instead of our relative example `require('./utilities')` shown above. |
0 commit comments