1

我想与它的父模块共享一个模式子模块的下划线混合。这是我的设置:

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

4

1 回答 1

0

我想我明白了!我需要稍微改变一下我的树:

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

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

于 2013-11-01T21:23:26.923 回答