【发布时间】:2013-11-02 05:23:26
【问题描述】:
我想与它的父模块共享一个模式子模块的下划线混合。这是我的设置:
.
├── 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'));
当我运行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 已在子模块 (In submodule : Hello) 中注册。但是,_.capitalize 在主模块中是未定义的。
如何让模块共享 mixin?
【问题讨论】:
-
问题是
submodule有它自己的下划线。您可以使用require('submodule/node_modules/underscore')从主模块访问它。 NPM 版本控制模型甚至允许submodule安装不同版本的下划线,例如,它可能是来自 git 的一些自定义构建。 -
@LeonidBeschastny 谢谢。
submodule/node_modules/underscore是我唯一有下划线的地方。我认为如果 require 从同一个位置抓取它,它会在整个过程中被缓存。是否可以不必每次都执行 require('submodule/node_modules/underscore') 来做到这一点? -
require('underscore')在主模块中工作的事实意味着您确实安装了另一个下划线。子模块可以通过require作为自己的依赖访问其父子模块,但不能相反。 -
@LeonidBeschastny 你是对的。我看了
require.cache,确实还有另一个下划线。我是在假设下 require 遍历 node_modules 树来找到模块。
标签: javascript node.js underscore.js npm