javascript - 跨 Node.js 模块共享下划线 mixins

标签 javascript node.js underscore.js npm

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

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

相关文章:

javascript - Underscore.js 模板仅在 IE 8/9 中抛出语法错误

javascript - 为什么 jCanvas 绘制错误的像素?

javascript - 尝试将 html 页面加载到页面上

javascript - 使用 jQuery 拦截表单提交

node.js - 如何上传文件,然后在 Node.Js Express 应用程序中显示其内容?

javascript - 使用 Underscorejs 按位置合并两组 js 对象

javascript - jquery 自动完成 - 字符串数组

javascript - 如何在 JavaScript (ES6) 中测试基于生成器的流控制?

javascript - 从 nodeJs 请求 font Awesome 文件发送回错误的数据/文件

javascript - 从主干 View 中的模板获取 DOM 元素