如何在另一个文件中使用不同导出语法调用两个函数?

huangapple go评论77阅读模式
英文:

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&#39;s working fine and I don&#39;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&#39;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(&#39;Hello World!&#39;);
  }

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(&quot;./main&quot;)

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(&#39;Hello World!&#39;);
  }
function sayHi(){
  console.log(&#39;Hi World&#39;);
  }

module.exports = {fun, sayHi}


//call.js
const { fun, sayHi } = require(&quot;./main&quot;)
fun()
sayHi()

huangapple
  • 本文由 发表于 2023年1月7日 01:40:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75034321.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定