在 Node.js 中声明多个 module.exports

新手上路,请多包涵

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

模块.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?

原文由 Ali 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 791
2 个回答

您可以执行以下操作:

 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');

原文由 mash 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

 module.exports = {
   function1,
   function2,
   function3
}

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

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

然后您可以通过以下方式调用每个函数:

 myFunctions.function1
myFunctions.function2
myFunctions.function3

原文由 Devorah 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题