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

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 = (function () {
    'use strict';

    var foo = function () {
        return {
            public_method: function () {}
        };
    };

    var bar = function () {
        return {
            public_method: function () {}
        };
    };

    return {
        module_a: foo,
        module_b: bar
    };
}());

其他回答

您也可以使用这种方法

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

or

exports.func1 = ...
exports.func2 = ...
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
    };
}());

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

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

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

您可以使用以下代码片段导出这些函数,

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

你可以使用这个代码片段来使用导出的函数,

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

add(1,2);
sub(1,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');

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

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