将可选parameter passing给require()

所以,我有这个问题 – 当我有JavaScript或节点的问题不可避免地是我的编码是问题;)

所以在嘲笑的风险,这是问题:

我有一个模块,它有一个可选的参数configuration

使用标准模式,这是我有:

module.exports = function(opts){ return { // module instance }; } 

在调用代码中有这个

 var foo = require('bar')({option: value}) 

如果没有选项可以通过,代码如下所示

 var foo = require('bar')({}) 

这有点看起来丑陋

所以,我想这样做

 var foo = require('bar') 

这不起作用,因为出口是函数调用

所以,到这个问题的肉

a)有没有办法达到这个崇高的目标? b)将parameter passing给模块有更好的模式吗?

非常感谢 – 而且我希望一旦笑声过去了,您将能够以我的方式发送一些帮助:)

而不是完全删除函数调用,您可以使选项参数选项删除需要一个空的对象:

 module.exports = function(opts) { opts = opts || {}; return { // module instance }; } 

它不完全删除()的需要,但比({})更好。

tldr :坚持require('foo')('bar');

没有办法传递额外的参数来require 。 这是源代码 ,注意它只是一个参数:

 Module.prototype.require = function(path) { assert(util.isString(path), 'path must be a string'); assert(path, 'missing path'); return Module._load(path, this); }; 

如果你真的真的想避免()() ,你可以尝试这样的事情:

b.js

 'use strict'; module.exports = { x: 'default', configure: function (x) { this.x = x; }, doStuff: function () { return 'x is ' + this.x; } }; 

a.js

 'use strict'; var b = require('./b'); // Default config: console.log(b.doStuff()); // 'x is default' // Reconfigure: b.configure(42); console.log(b.doStuff()); // 'x is 42' 

但是我认为这是更丑陋的…坚持原来的想法。