代码之家  ›  专栏  ›  技术社区  ›  Rado Harutyunyan

通过节点js中的某些条件导出模块函数

  •  -2
  • Rado Harutyunyan  · 技术社区  · 6 年前
    module.exports ={
        "test1": {  
            moduleno: 1,
            modulename: 'test1'
        },
    
    "test2": {  
        moduleno: 2,
        modulename: 'test2'
    }
    

    };

    伙计们,我需要帮助,我该怎么做?if condition1:仅导出test1模块,否则导出test2模块。

    2 回复  |  直到 6 年前
        1
  •  0
  •   clovis1122    6 年前

    您可以执行以下操作:

    const app = {};
    module.exports = app;
    
    app.moduleToExport = condition ? module1 : module2;
    

    将对象指定给 module.exports ,您正在动态创建新对象。使用这种方法,您还可以创建一个新对象,但在变量应用程序中保留对该对象的引用,以便您可以有条件地导出模块或执行所需的任何其他逻辑。

        2
  •  0
  •   eum602    6 年前

    我建议你这样做:

       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
    

    我希望这有帮助