英文:
How to call two functions with different export syntax in another file?
问题
//call.js
const main = require('./main');
main.fun();
但我收到了一个错误 TypeError: main.fun is not a function
。如何修复这个错误?
<details>
<summary>英文:</summary>
I have these two functions and I can call ```fun()``` in the same file and it's working fine and I don't want to change this ```module.exports = function(controller) {
//some code
}``` code
//main.js
module.exports = function(controller) {
//some code
}
function fun(){
console.log('Hello World!');
}
module.exports = {fun}
Now what I want to do is I want to call the function ```fun()``` in a different file
//call.js
const main = require('./main')
main.fun();
but I'm getting an error ```TypeError: main.fun is not a function```.
How do I fix this error
</details>
# 答案1
**得分**: 2
你可以赋值给`module.exports`的属性:
```javascript
module.exports.fun = fun;
但通常情况下,如果你想从一个模块中导出多个函数,你会将module.exports
设置为包含所有函数的对象。
英文:
You can assign to properties of module.exports
:
module.exports.fun = fun;
But normally if you want to export multiple functions from a module, you set module.exports
to an object containing all the functions.
答案2
得分: 0
我会通过在main.js文件的最后一行导出来实现这个,就像这样:
//main.js
function fun(){
console.log('Hello World!');
}
module.exports = {fun}
然后,你可以在call.js文件中导入它,通过在你的“require”行中解构函数的名称,然后像调用call.js文件中的任何其他本地函数一样调用它:
//call.js
const { fun } = require("./main")
fun()
这种格式很有帮助,因为你可以在导出和导入的大括号中不重复相似的代码行添加更多的函数名称:
//main.js
function fun(){
console.log('Hello World!');
}
function sayHi(){
console.log('Hi World');
}
module.exports = {fun, sayHi}
//call.js
const { fun, sayHi } = require("./main")
fun()
sayHi()
英文:
I would do it by exporting from main.js in the last line of the main.js file like this:
//main.js
function fun(){
console.log('Hello World!');
}
module.exports = {fun}
You can then import it into your call.js file by destructuring the name of the function in your 'require' line and then just calling it like any other function that is native to the call.js file:
//call.js
const { fun } = require("./main")
fun()
This format is helpful because you can just keep adding more function names between the brackets for exports and imports without repeating similar lines of code:
//main.js
function fun(){
console.log('Hello World!');
}
function sayHi(){
console.log('Hi World');
}
module.exports = {fun, sayHi}
//call.js
const { fun, sayHi } = require("./main")
fun()
sayHi()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论