【问题标题】:Best way to inject config into a module将配置注入模块的最佳方法
【发布时间】:2018-10-20 20:02:00
【问题描述】:

我希望我的模块 something.js 依赖于配置,但我不希望它依赖于配置本身 require,我希望我的编辑器继续能够分析模块并显示自动完成。有没有一种干净的方法可以做到这一点?不幸的是,这是一个让编辑感到困惑的解决方案。

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 something = require ('./something'); 是否也希望模块使用这些选项进行初始化?
  • @james 和 femioni - 是的,抱歉不清楚,将编辑

标签: javascript node.js module require


【解决方案1】:

假设Something 应该是单例,我会这样做:

const _inst = null;

const _init = options => {
  if (!_inst) {
    _inst = new Something(options);
  }
  return _inst;    
}

class Something {
  constructor(options) {
  }

  method() {
  }
}

module.exports = _init;

something 的第一个包含将创建实例,然后后续调用(无论是否传递选项)将始终返回相同的实例。

只有警告,这 与您想要的用法略有不同,这将涉及您必须两次调用一个函数,即

// First use
const something1 = require ('./something')(options);

// All subsequent uses
const something2 = require ('./something')();

还有很多其他方法可以做到这一点,即多次导出,但以上可能是最接近您所追求的语法。如果您可以访问 import 语法(您可以通过 Babel 访问),那么多重导入可能是更简洁的方式,即导出 init 函数和实例本身。

【讨论】:

    猜你喜欢
    • 2014-11-15
    • 2012-11-12
    • 2013-09-14
    • 1970-01-01
    • 2011-11-30
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多