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

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 = {
   function1,
   function2,
   function3
}

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

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

然后你可以通过调用:

myFunctions.function1
myFunctions.function2
myFunctions.function3

其他回答

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

module.exports = {
   function1,
   function2,
   function3
}

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

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

然后你可以通过调用:

myFunctions.function1
myFunctions.function2
myFunctions.function3

你可以这样做:

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.exports.eat =吃; 函数eat() { …… 返回* *的东西; }; Module.exports.sleep =睡眠; 函数sleep() { …… 返回* *的东西; };

注意,导出函数时并没有调用它们。 然后,在要求模块时,您可以要求为:-

Const task = require(__dirname + "/task.js"); //task是文件的名称 Let eat = task.eat(); Let sleep = task.sleep();

除了@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导出的,你可以写:

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