我想从一个模式子模块与其父模块共享一个下划线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'));./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在主模块中未定义。
如何让模块共享mixins?
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?
最满意答案
我想我想通了! 我需要改变一下我的树:
├── index.js └── node_modules ├── submodule │ ├── index.js │ └── package.json └── underscore ├── LICENSE ├── README.md ├── package.json ├── underscore-min.js └── underscore.js现在只有根模块具有'下划线'模块。 我猜测在子模块中执行require('下划线')要么使用主模块中的require的缓存,要么向上遍历树以找到它。
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.jsNow 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.
更多推荐
发布评论