我想要实现的是创建一个包含多个函数的模块。
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?
发布于 2013-05-19 11:11:14
你可以这样做:
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');
发布于 2016-07-04 05:47:15
要导出多个函数,您可以像这样列出它们:
module.exports = {
function1,
function2,
function3
}
然后在另一个文件中访问它们:
var myFunctions = require("./lib/file.js")
然后,您可以通过调用以下命令来调用每个函数:
myFunctions.function1
myFunctions.function2
myFunctions.function3
发布于 2019-02-27 13:30:20
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>);
https://stackoverflow.com/questions/16631064
复制相似问题