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

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(arg) {
    if(arg instanceof String) {
         return doStringThing.apply(this, arguments);
    }else{
         return doObjectThing.apply(this, arguments);
    }
};

其他回答

你也可以像这样导出

const func1 = function (){some code here}
const func2 = function (){some code here}
exports.func1 = func1;
exports.func2 = func2;

或 对于这样的匿名函数

    const func1 = ()=>{some code here}
    const func2 = ()=>{some code here}
    exports.func1 = func1;
    exports.func2 = func2;

module1.js:

var myFunctions = { 
    myfunc1:function(){
    },
    myfunc2:function(){
    },
    myfunc3:function(){
    },
}
module.exports=myFunctions;

main.js

var myModule = require('./module1');
myModule.myfunc1(); //calling myfunc1 from module
myModule.myfunc2(); //calling myfunc2 from module
myModule.myfunc3(); //calling myfunc3 from module

一种方法是在模块中创建一个新对象,而不是替换它。

例如:

var testone = function () {
    console.log('test one');
};
var testTwo = function () {
    console.log('test two');
};
module.exports.testOne = testOne;
module.exports.testTwo = testTwo;

然后打电话

var test = require('path_to_file').testOne:
testOne();

您也可以使用这种方法

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

or

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

使用export关键字

module.js

export {method1, method2}

然后导入到main.js中

import {method1, method2) from "./module"