Javascript 将配置注入模块的最佳方法
我希望我的模块Javascript 将配置注入模块的最佳方法,javascript,node.js,module,require,Javascript,Node.js,Module,Require,我希望我的模块something.js依赖配置,但我不希望它需要配置本身,我希望我的编辑器能够继续分析模块并显示自动完成。有没有干净的方法可以做到这一点?不幸的是,这里有一个解决方案让编辑们感到困惑 class Something { constructor (options) { ... } method () { ... } } module.exports = options => module.exports =
something.js
依赖配置,但我不希望它需要配置本身,我希望我的编辑器能够继续分析模块并显示自动完成。有没有干净的方法可以做到这一点?不幸的是,这里有一个解决方案让编辑们感到困惑
class Something {
constructor (options) {
...
}
method () {
...
}
}
module.exports = options => module.exports = exports = new Something (options);
在使用中:
// First use
const something1 = require ('./something')(options);
// All subsequent uses (expecting something1 to deep equal something2)
const something2 = require ('./something');
假设
某物
应该是一个单身汉,我会这样做:
const _inst = null;
const _init = options => {
if (!_inst) {
_inst = new Something(options);
}
return _inst;
}
class Something {
constructor(options) {
}
method() {
}
}
module.exports = _init;
首先include ofsomething
将创建实例,然后后续调用(无论是否传递了选项)将始终返回相同的实例
只需注意,这与您期望的用法略有不同,这将涉及到您必须两次调用一个函数,即
// First use
const something1 = require ('./something')(options);
// All subsequent uses
const something2 = require ('./something')();
还有多种其他方法可以实现这一点,即多次导出,但上述方法可能与您所追求的语法最为接近。如果您可以访问
import
语法(您可以通过Babel访问该语法),那么多个导入可能是更简洁的方式,即导出init
函数和实例本身。因此,在后续调用中,您会期望相同的实例?const something=require('./something')
您是否也希望模块使用这些选项进行初始化?@james and femioni-是的,对不起,不清楚,将进行编辑