【问题标题】:Declare multiple module.exports in Node.js在 Node.js 中声明多个 module.exports
【发布时间】:2013-05-13 22:07:14
【问题描述】:

我想要实现的是创建一个包含多个功能的模块。

module.js:

module.exports = function(firstParam) { console.log("You did it"); },
module.exports = function(secondParam) { console.log("Yes you did it"); }, 
// This may contain more functions

main.js:

var foo = require('module.js')(firstParam);
var bar = require('module.js')(secondParam);

我遇到的问题是 firstParam 是一个对象类型,而 secondParam 是一个 URL 字符串,但是当我遇到它时,它总是抱怨类型错误。

在这种情况下如何声明多个 module.exports?

【问题讨论】:

  • 对于任何来这里想知道如何导出多个require 方法或require 方法和其他功能的组合的人,答案是here

标签: node.js module


【解决方案1】:

你可以这样做:

module.exports = {
    method: function() {},
    otherMethod: function() {},
};

或者只是:

exports.method = function() {};
exports.otherMethod = function() {};

然后在调用脚本中:

const myModule = require('./myModule.js');
const method = myModule.method;
const otherMethod = myModule.otherMethod;
// OR:
const {method, otherMethod} = require('./myModule.js');

【讨论】:

  • 我在这里没有使用module.method...只有exports.method,它只是对module.exports.method的引用,所以行为方式相同。唯一的区别是我们没有定义module.exports,所以它默认为{},除非我弄错了。
  • @mash 是否可以在另一个文件中使用:var otherMethod = require('module.js')(otherMethod);?即,该行是否需要 otherMethod 函数,就好像它是页面上的唯一函数并且导出为:module.exports = secondMethod;
  • @YPCrumble 你可以做var otherMethod = require('module.js').otherMethod
【解决方案2】:

您可以编写一个在其他函数之间手动委托的函数:

module.exports = function(arg) {
    if(arg instanceof String) {
         return doStringThing.apply(this, arguments);
    }else{
         return doObjectThing.apply(this, arguments);
    }
};

【讨论】:

  • 这是一种实现函数重载的方法,但不是很……优雅。我认为 Mash 的回答更简洁,更能体现意图。
【解决方案3】:

这只是我的参考,因为我试图达到的目标可以通过这个来实现。

module.js

我们可以这样做

    module.exports = function ( firstArg, secondArg ) {

    function firstFunction ( ) { ... }

    function secondFunction ( ) { ... }

    function thirdFunction ( ) { ... }

      return { firstFunction: firstFunction, secondFunction: secondFunction,
 thirdFunction: thirdFunction };

    }

main.js

var name = require('module')(firstArg, secondArg);

【讨论】:

    【解决方案4】:
    module.exports = (function () {
        'use strict';
    
        var foo = function () {
            return {
                public_method: function () {}
            };
        };
    
        var bar = function () {
            return {
                public_method: function () {}
            };
        };
    
        return {
            module_a: foo,
            module_b: bar
        };
    }());
    

    【讨论】:

      【解决方案5】:

      使用这个

      (function()
      {
        var exports = module.exports = {};
        exports.yourMethod =  function (success)
        {
      
        }
        exports.yourMethod2 =  function (success)
        {
      
        }
      
      
      })();
      

      【讨论】:

        【解决方案6】:

        一种方法是在模块中创建一个新对象,而不是替换它。

        例如:

        var testone = function () {
            console.log('test one');
        };
        var testTwo = function () {
            console.log('test two');
        };
        module.exports.testOne = testOne;
        module.exports.testTwo = testTwo;
        

        打电话

        var test = require('path_to_file').testOne:
        testOne();
        

        【讨论】:

          【解决方案7】:

          要导出多个函数,您可以像这样列出它们:

          module.exports = {
             function1,
             function2,
             function3
          }
          

          然后在另一个文件中访问它们:

          var myFunctions = require("./lib/file.js")
          

          然后你可以通过调用来调用每个函数:

          myFunctions.function1
          myFunctions.function2
          myFunctions.function3
          

          【讨论】:

          • 您也可以在访问它们时这样做:const { function1, function2, function3 } = require("./lib/file.js") 允许您直接调用它们(例如function1 而不是myFunctions.function1
          • 哇,非常感谢您的回答。它拯救了我的一天:)
          【解决方案8】:

          除了@mash 回答,我建议您始终执行以下操作:

          const method = () => {
             // your method logic
          }
          
          const otherMethod = () => {
             // your method logic 
          }
          
          module.exports = {
              method, 
              otherMethod,
              // anotherMethod
          };
          

          请注意:

          • 您可以从otherMethod 致电method,您将非常需要这个
          • 您可以在需要时快速将方法隐藏为私有方法
          • 这对于大多数 IDE 来说更容易理解和自动完成您的代码;)
          • 您也可以使用相同的技术进行导入:

            const {otherMethod} = require('./myModule.js');

          【讨论】:

          • 请注意,这使用了 es6 对象初始化快捷方式 - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
          • 这是更好的答案恕我直言,因为它解决了从 otherMethod 访问方法的问题。感谢您指出这一点。
          • 我正在寻找如何写const {otherMethod} = require('./myModule.js'); 这个。您将这种从 {} 导入方法的方法称为什么?
          • @Franva 当您在作业右侧执行 require(./myModule.js) 时,您实际上是将整个模块作为单个对象导入,然后当您在作业左侧执行 const {otherMethod} 时,您就是做一些叫做“解构分配”的事情,你可以在 MDN 中阅读更多关于它的信息:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
          • 但是,如果我的方法是异步的,我想在 otherMethod 中调用方法
          【解决方案9】:

          如果文件是用 ES6 export 写的,你可以写:

          module.exports = {
            ...require('./foo'),
            ...require('./bar'),
          };
          

          【讨论】:

            【解决方案10】:

            module.js:

            const foo = function(<params>) { ... }
            const bar = function(<params>) { ... } 
            
            //export modules
            module.exports = {
                foo,
                bar 
            }
            

            main.js:

            // import modules
            var { foo, bar } = require('module');
            
            // pass your parameters
            var f1 = foo(<params>);
            var f2 = bar(<params>);
            

            【讨论】:

              【解决方案11】:

              module1.js:

              var myFunctions = { 
                  myfunc1:function(){
                  },
                  myfunc2:function(){
                  },
                  myfunc3:function(){
                  },
              }
              module.exports=myFunctions;
              

              main.js

              var myModule = require('./module1');
              myModule.myfunc1(); //calling myfunc1 from module
              myModule.myfunc2(); //calling myfunc2 from module
              myModule.myfunc3(); //calling myfunc3 from module
              

              【讨论】:

                【解决方案12】:

                两种类型的模块导入和导出。

                类型 1 (module.js):

                // module like a webpack config
                const development = {
                  // ...
                };
                const production = {
                  // ...
                };
                
                // export multi
                module.exports = [development, production];
                // export single
                // module.exports = development;
                

                类型 1 (main.js):

                // import module like a webpack config
                const { development, production } = require("./path/to/module");
                

                类型 2 (module.js):

                // module function no param
                const module1 = () => {
                  // ...
                };
                // module function with param
                const module2 = (param1, param2) => {
                  // ...
                };
                
                // export module
                module.exports = {
                  module1,
                  module2
                }
                

                类型 2 (main.js):

                // import module function
                const { module1, module2 } = require("./path/to/module");
                

                如何使用导入模块?

                const importModule = {
                  ...development,
                  // ...production,
                  // ...module1,
                  ...module2("param1", "param2"),
                };
                

                【讨论】:

                • 在 type1 中,您不能导出为数组并导入为对象
                【解决方案13】:

                你也可以这样导出

                const func1 = function (){some code here}
                const func2 = function (){some code here}
                exports.func1 = func1;
                exports.func2 = func2;
                

                或 对于这样的匿名函数

                    const func1 = ()=>{some code here}
                    const func2 = ()=>{some code here}
                    exports.func1 = func1;
                    exports.func2 = func2;
                

                【讨论】:

                  【解决方案14】:

                  如果你在模块文件中声明一个类而不是简单对象

                  文件:UserModule.js

                  //User Module    
                  class User {
                    constructor(){
                      //enter code here
                    }
                    create(params){
                      //enter code here
                    }
                  }
                  class UserInfo {
                    constructor(){
                      //enter code here
                    }
                    getUser(userId){
                      //enter code here
                      return user;
                    }
                  }
                  
                  // export multi
                  module.exports = [User, UserInfo];
                  

                  主文件:index.js

                  // import module like
                  const { User, UserInfo } = require("./path/to/UserModule");
                  User.create(params);
                  UserInfo.getUser(userId);
                  

                  【讨论】:

                    【解决方案15】:

                    你也可以使用这种方法

                    module.exports.func1 = ...
                    module.exports.func2 = ...
                    

                    exports.func1 = ...
                    exports.func2 = ...
                    

                    【讨论】:

                      【解决方案16】:

                      有多种方法可以做到这一点,下面提到了一种方法。 假设你有这样的 .js 文件。

                      let add = function (a, b) {
                         console.log(a + b);
                      };
                      
                      let sub = function (a, b) {
                         console.log(a - b);
                      };
                      

                      你可以使用下面的代码sn -p来导出这些函数,

                       module.exports.add = add;
                       module.exports.sub = sub;
                      

                      你可以使用这个代码sn-p来使用导出的函数,

                      var add = require('./counter').add;
                      var sub = require('./counter').sub;
                      
                      add(1,2);
                      sub(1,2);
                      

                      我知道这是一个迟到的回复,但希望这会有所帮助!

                      【讨论】:

                        【解决方案17】:

                        在此处添加以寻求帮助:

                        此代码块将有助于将多个插件添加到 cypress index.js 插件 -> cypress-ntlm-authcypress env 文件选择

                        const ntlmAuth = require('cypress-ntlm-auth/dist/plugin');
                        const fs = require('fs-extra');
                        const path = require('path');
                        
                        const getConfigurationByFile = async (config) => {
                          const file = config.env.configFile || 'dev';
                          const pathToConfigFile = path.resolve(
                            '../Cypress/cypress/',
                            'config',
                            `${file}.json`
                          );
                          console.log('pathToConfigFile' + pathToConfigFile);
                          return fs.readJson(pathToConfigFile);
                        };
                        
                        module.exports = async (on, config) => {
                          config = await getConfigurationByFile(config);
                          await ntlmAuth.initNtlmAuth(config);
                          return config;
                        };
                        

                        【讨论】:

                          【解决方案18】:

                          在您的节点模块中,您可以导出各种功能,例如:

                          module.exports.eat = eat;
                          
                          function eat() {
                            .......
                            return *something*;
                          };
                          
                          module.exports.sleep = sleep;
                          
                          function sleep() {
                            .......
                            return *something*;
                          };

                          请注意,您在导出函数时不会调用它们。 然后在需要模块时,您可以要求:-

                          const task = require(__dirname + "/task.js");
                          //task is the name of the file
                          
                          let eat = task.eat();
                          let sleep = task.sleep();

                          【讨论】:

                            猜你喜欢
                            • 1970-01-01
                            • 2012-08-31
                            • 2017-05-31
                            • 1970-01-01
                            • 1970-01-01
                            • 2020-08-10
                            • 2011-10-31
                            • 2015-08-19
                            相关资源
                            最近更新 更多