Home > Enterprise >  How to call two functions with different export syntax in another file?
How to call two functions with different export syntax in another file?

Time:01-07

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

CodePudding user response:

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.

CodePudding user response:

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()
  • Related