我想与其父模块共享模式子模块中的下划线混合。这是我的设置:
.
├── 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?
最佳答案
我想我已经明白了!我需要稍微改变一下我的树:
├── index.js
└── node_modules
├── submodule
│ ├── index.js
│ └── package.json
└── underscore
├── LICENSE
├── README.md
├── package.json
├── underscore-min.js
└── underscore.js
现在只有根模块具有“下划线”模块。我猜测在子模块中执行 require('underscore') 要么使用主模块中 require 的缓存,要么向上遍历树来找到它。
关于javascript - 跨 Node.js 模块共享下划线 mixins,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19735081/