Share underscore mixins across node.js modules


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
        │       ├──
        │       ├── package.json
        │       ├── underscore-min.js
        │       └── underscore.js
        └── package.json


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

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


var _ = require('underscore');

  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

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


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
        ├── 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


There is currently no discussion for this recipe.

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