Share underscore mixins across node.js modules

Problem

I'd like to share an underscore mixin from a mode submodule with its parent module. Here's my setup:

.
├── index.js
└── node_modules
    └── submodule
        ├── index.js
        ├── node_modules
        │   └── underscore
        │       ├── LICENSE
        │       ├── README.md
        │       ├── package.json
        │       ├── underscore-min.js
        │       └── underscore.js
        └── package.json

./index.js:

var submodule = require('submodule')
  , _ = require('underscore');

console.log('In main module : %s', _.capitalize('hello'));

./node_modules/submodule/index.js:

var _ = require('underscore');

_.mixin({
  capitalize : function(string) {
    return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
  }
});

console.log('In submodule : %s', _.capitalize('hello'));

When i run node index.js I get the following output:

In submodule : Hello

/Users/lxe/devel/underscore-test/index.js:4
console.log('In main module : %s', _.capitalize('hello'));
                                     ^
TypeError: Object function (obj) {
    if (obj instanceof _) return obj;
    if (!(this instanceof _)) return new _(obj);
    this._wrapped = obj;
  } has no method 'capitalize'

As you can see, the mixin was registered in submodule (In submodule : Hello). However, _.capitalize is undefined in the main module.

How can I make the modules share the mixins?

Problem courtesy of: lxe

Solution

I think I figured it out! I needed to change my tree a bit:

├── index.js
└── node_modules
    ├── submodule
    │   ├── index.js
    │   └── package.json
    └── underscore
        ├── LICENSE
        ├── README.md
        ├── package.json
        ├── underscore-min.js
        └── underscore.js

Now only the root module has the 'underscore' module. I'm guessing doing require('underscore') in the submodule either uses a cache of the require from the main module, or traverses the tree upwards to find it.

Solution courtesy of: lxe

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.