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

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.func1 = ...
module.exports.func2 = ...

or

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

其他回答

您也可以使用这种方法

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

or

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

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

module.exports = {
   function1,
   function2,
   function3
}

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

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

然后你可以通过调用:

myFunctions.function1
myFunctions.function2
myFunctions.function3
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
    };
}());

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

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

你可以写一个函数来手动委托其他函数:

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