【问题标题】:export a module function by some condition in Node js在 Node js 中通过某些条件导出模块函数
【发布时间】:2019-01-12 19:53:04
【问题描述】:
module.exports ={
    "test1": {  
        moduleno: 1,
        modulename: 'test1'
    },

"test2": {  
    moduleno: 2,
    modulename: 'test2'
}

};

各位,我需要帮助,我该怎么做? if condition1: 只导出 test1 模块,否则导出 test2 模块。

【问题讨论】:

  • 你试过什么?你知道if 语句是如何工作的吗?

标签: javascript node.js ecmascript-6 module


【解决方案1】:

您可以执行以下操作:

const app = {};
module.exports = app;

app.moduleToExport = condition ? module1 : module2;

当您将对象分配给module.exports 时,您正在动态创建一个新对象。使用这种方法,您还可以创建一个新对象,但在变量 app 中保存对它的引用,以便您可以有条件地导出模块或执行您需要的任何其他逻辑。

【讨论】:

    【解决方案2】:

    让我建议这样做:

       const app = {}
    
        app.test1 = {
            moduleno: 1,
            modulename: 'test1'
        }
    
        app.test2 = {
            moduleno: 2,
            modulename: 'test2'
        }
    
       //implement your condition in order to determine wich module to export
       //for example:
       const moduleToExport = 1 //Actually it may depends on some process 
       condition or another general condition
       const exported = moduleToExport === 1 ? app.test1:app.test2
       module.exports  = exported
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-28
      • 2017-03-05
      • 1970-01-01
      • 1970-01-01
      • 2015-06-14
      相关资源
      最近更新 更多