繁体   English   中英

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

[英]How to call two functions with different export syntax in another file?

我有这两个函数,我可以在同一个文件中调用fun() ,它工作正常,我不想改变这个module.exports = function(controller) { //some code } code

//main.js
module.exports = function(controller) {
//some code
}

function fun(){
  console.log('Hello World!');
}
module.exports = {fun}

现在我想做的是在另一个文件中调用 function fun()

//call.js
const main = require('./main')

main.fun();

但我收到错误TypeError: main.fun is not a function 我该如何解决这个错误

您可以分配给module.exports的属性:

module.exports.fun = fun;

但通常情况下,如果你想从一个模块中导出多个函数,你可以将module.exports设置为包含所有函数的 object。

我会通过在 main.js 文件的最后一行从 main.js 导出来做到这一点,如下所示:

//main.js

function fun(){
  console.log('Hello World!');
  }

module.exports = {fun}

然后,您可以通过在“require”行中解构 function 的名称,然后像调用 call.js 文件中的任何其他 function 一样调用它,将其导入到 call.js 文件中:

//call.js

const { fun } = require("./main")

fun()

这种格式很有用,因为您可以在导出和导入的括号之间继续添加更多 function 名称,而无需重复类似的代码行:

//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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM