将可选参数传递给require()函数

5

我有这个问题-当我遇到JavaScript或node的问题时,必然是我的编程出了问题;)

冒着被嘲笑的风险,这就是问题所在:

我有一个模块,其中有一个可选参数config

按照标准模式,我的代码如下:

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

在调用代码中有这个:

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

如果没有要传递的选项,代码将如下所示。
var foo = require('bar')({})

这个看起来有点丑陋

所以,我想要做这个

var foo = require('bar')

这不起作用,因为exports是一个函数调用

所以,问题的核心是:

a) 有没有办法实现这个崇高的目标? b) 是否有更好的模块参数传递模式?

非常感谢 - 希望一旦笑声过去,您能够给我提供帮助 :)


我的意思是,如果你唯一的问题是“它很丑”,那么你不必把所有东西都写在一行上。 - loganfsmyth
2
我该说什么呢?我想在我的编程风格中实现“禅”;空的({})就是太丑陋了。我的代码应该是美丽的... - jmls
1
它还应该是功能性的并且易于理解。 - Stephen
2个回答

4

不要完全删除函数调用,你可以将选项参数转换为可选,这样就无需使用空对象:

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

它并不能完全取代 () 但是比 ({}) 更好。


3

简而言之: 使用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'

但我认为这样更丑...坚持原来的想法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接