在 Node.js 中声明多个 module.exports [英] Declare multiple module.exports in Node.js
本文介绍了在 Node.js 中声明多个 module.exports的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要实现的是创建一个包含多个功能的模块.
What I'm trying to achieve is to create one module that contains multiple functions in it.
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 字符串,但是当我遇到它时它总是抱怨类型错误.
The problem I have is that the firstParam
is an object type and the secondParam
is a URL string, but when I have that it always complains that the type is wrong.
在这种情况下如何声明多个 module.exports?
How can I declare multiple module.exports in this case?
推荐答案
您可以执行以下操作:
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');
这篇关于在 Node.js 中声明多个 module.exports的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文