Javascript 跨node.js模块共享下划线混合

Javascript 跨node.js模块共享下划线混合,javascript,node.js,underscore.js,npm,Javascript,Node.js,Underscore.js,Npm,我想将模式子模块中的下划线mixin与其父模块共享。以下是我的设置: . ├── index.js └── node_modules └── submodule ├── index.js ├── node_modules │   └── underscore │   ├── LICENSE │   ├── README.md │   ├── package.json

我想将模式子模块中的下划线mixin与其父模块共享。以下是我的设置:

.
├── 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'));
var _ = require('underscore');

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

console.log('In submodule : %s', _.capitalize('hello'));
/node\u modules/submodule/index.js:

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

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

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

console.log('In submodule : %s', _.capitalize('hello'));
当我运行
node index.js
时,我得到以下输出:

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'
如您所见,mixin已在子模块中注册(
在子模块中:Hello
)。但是,
\大写
在主模块中未定义


我怎样才能让模块共享混音呢?

我想我已经解决了!我需要稍微改变一下我的树:

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

现在只有根模块具有“下划线”模块。我猜子模块中的require(“下划线”)要么使用主模块中require的缓存,要么向上遍历树以找到它。

问题在于
子模块有自己的下划线。您可以使用
require('submodule/node\u modules/下划线')
从主模块访问它。NPM版本控制模型甚至允许子模块安装不同版本的下划线,例如,它可能是一些来自git的自定义版本。@LeonidBeschastny谢谢<代码>子模块/节点\模块/下划线
是我唯一有下划线的地方。我认为如果require从同一个位置抓取它,它就会在整个过程中被缓存。不必每次都执行require('submodule/node_modules/underline')就可以执行此操作吗?
require('underline')
在主模块中工作,这意味着您确实安装了另一个下划线。子模块可以通过
require
作为其自身的依赖项来访问其父子模块,但并非相反。@LeonidBeschastny您是正确的。我查看了
require.cache
,确实还有一个下划线。我假设require遍历node_modules树来查找模块。实际上,它首先查找本地
下划线。如果没有本地的
下划线
,那么它将使用其父级的
下划线
。在这个解决方案中,我唯一不喜欢的是您需要从
子模块
包.json
中删除
下划线