要给出更详细的答案,有几种方法可以做到这一点。第一种方法是将 module.exports 与对象一起使用。这将允许您使用require(或者,使用像 babel 或 webpack 这样的编译器,import)来导入模块,并且您可以调用对象中的任何函数。这是使用@MaxxiBoi 的响应方式。
// File 1
module.exports = {
"myFunction1": (arg1, arg2) => {
console.log("Function 1 with 2 args: "+ arg1 + " " + arg2);
},
"myFunction2": () => {
console.log("Function 2");
}
}
// File 2
const myModule = require("./file1.js");
myModule.myFunction1(null, "Hi"); // Logs "Function 1 with 2 args: null Hi"
myModule.myFunction2(); // Logs "Function 2"
虽然这在您想要输出多个函数的情况下很有用,但如果您只想要每个模块一个函数,我不会这样做。
第二种方法是使用带有变量或函数的 module.exports,而不是对象。这可以减少混乱并使其更易于理解。
// File 1
module.exports = myFunction1(arg1, arg2) {
console.log("Function 1 with 2 args: " + arg1 + " " + arg2);
}
// File 2
const myFunction = require("./file1.js");
myFunction(null, "Hi"); // Logs "Function 1 with 2 args: null Hi"
最后,还有另一种使用 ES5 或 ES6(在本例中我使用 ES6)创建构造函数的方法,这将允许您向其中传递更多变量,然后您可以在该类中引用这些变量。在此示例中,我使用 Discord.js 客户端并从构造函数中获取客户端的名称。假设客户的名字是“George”。
// File 1
module.exports = class MyClass {
constructor(client) {
this.client = client;
}
myFunction1(myVar2) {
console.log("Function 1 with 2 args: " + this.client.user.username + " " + myVar2);
}
myFunction2() {
console.log("Function 2");
}
}
// File 2
const MyClass = require("./MyClass.js");
const myClassInstance = new MyClass(client);
myClassInstance.myFunction1("Hi"); // Logs "Function1 with 2 args: George Hi"
myClassInstance.myFunction2(); // Logs "Function 2"
最后,这完全取决于您喜欢什么以及您想怎么做。每种方法都有其优缺点。如果您想了解更多关于我如何制作所有这些以及模块的一般工作原理,请查看Node.js docs explanation。要了解有关类(第三个模块中使用的类)的更多信息,请查看MDN documentation。希望我能够帮助您并为您提供选择。您可能还想查看this StackOverflow question,因为它可以解决您关于在不同目录中引用文件的问题。编码愉快!