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

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字符串,但当我有它总是抱怨类型是错误的。

我如何声明多个模块。在这种情况下出口?


当前回答

除了@mash的回答,我建议你经常做以下事情:

const method = () => {
   // your method logic
}

const otherMethod = () => {
   // your method logic 
}

module.exports = {
    method, 
    otherMethod,
    // anotherMethod
};

注意:

你可以从otherMethod调用method,你会非常需要这个 当需要时,可以快速将方法隐藏为私有 这对于大多数IDE来说更容易理解和自动完成你的代码;) 您也可以使用相同的技术导入: const {otherMethod} = require('./myModule.js');

其他回答

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

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

如果在模块文件中声明类而不是简单对象

文件:UserModule.js

//User Module    
class User {
  constructor(){
    //enter code here
  }
  create(params){
    //enter code here
  }
}
class UserInfo {
  constructor(){
    //enter code here
  }
  getUser(userId){
    //enter code here
    return user;
  }
}

// export multi
module.exports = [User, UserInfo];

主文件:index.js

// import module like
const { User, UserInfo } = require("./path/to/UserModule");
User.create(params);
UserInfo.getUser(userId);

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

module.exports = {
   function1,
   function2,
   function3
}

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

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

然后你可以通过调用:

myFunctions.function1
myFunctions.function2
myFunctions.function3

使用export关键字

module.js

export {method1, method2}

然后导入到main.js中

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

module.js:

const foo = function(<params>) { ... }
const bar = function(<params>) { ... } 

//export modules
module.exports = {
    foo,
    bar 
}

main.js:

// import modules
var { foo, bar } = require('module');

// pass your parameters
var f1 = foo(<params>);
var f2 = bar(<params>);