r42
Mix in node's require, some angular dependency injection look&feel and the ease of use of RequireJS and what do you get?
Dependency injection done right for Node.js!
WARNING
This library is a work in progress. It won't have anything stable before 0.1.0. Please use with care. Right now, even small version changes can (and probably will) break your code.
Getting started
Installation
npm install r42
Your first module
Let's code lib/toto.js :
define(function (path, fs, _, dep1, dep2) {
return ;
});
Configuring & lauching your project
var r42 = require('r42');
var path = require('path');
r42.config({
baseDir: path.join(__dirname, 'lib'),
paths: {
_: 'lodash',
library: '../vendor/library',
sub: '../sub'
},
});
r42.inject(function (toto) {
});
More complex dependencies
Module in subfolders
If you want to resolve complex names in subdirectories, you can use the optional
"replacer" argument of the define function. Here is an example:
define({
test: 'sub/folder/test',
}, function (test) {
});
The object maps an argument's name to the real module name locally. The argument name
will be replaced by the given module name before injection happens.
You can also use special r42 comments (looking like /*! module */
) before your argument
names:
define(function ( test) {
});
Note : spaces are optional in r42 comments.
Modules in the same folder
Sometimes, it is a pain to refer to a module in the same folder as you are right now.
r42 allows for a fine way to do so.
Using '$' to prefix your variable's name will automatically cause r42 to replace it
by your current module's "path". It also works to prefix files in the replacer object.
In a module 'module/toto.js'
define({
superSub: '$super/sub',
}, function (superSub, $sideFn, sideVal) {
});
Circular dependencies
Those are working "automatically" but you NEED to exports barebone objects on both modules
for it to work.
Here is an example:
In a module 'a.js'
define(function (b) {
return {
aFn: function () {
b.bFn();
},
};
});
In a module 'b.js'
define(function (a) {
return {
bFn: function () {
a.bFn();
},
};
});
Special APIs
Printing dependencies
Right now, even if the output is rather horrible, it might give some useful information so here is how to use it:
BEWARE: This really can go away in between versions right now, maybe replaced by something achieving
the same purpose but better designed. Don't use this for other purposes than debugging.
This function does not print modules handled by NPM right now.
var r42 = require('r42');
r42.config({
});
r42.inject(function () {
r42.dumpDeps();
});