【问题标题】:Share underscore mixins across node.js modules在 node.js 模块之间共享下划线 mixins
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

  • 其实是先寻找本地的underscore。如果没有本地underscore,则使用其父级的underscore
  • 我唯一不喜欢这个解决方案的是你需要从submodulepackage.json中删除underscore
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-14
  • 1970-01-01
  • 2016-12-09
  • 2016-04-20
  • 1970-01-01
  • 2019-09-19
相关资源
最近更新 更多