Home > front end >  How To Use Module Exports Properly In JavaScript
How To Use Module Exports Properly In JavaScript

Time:08-01

I just started learning JS and when i try to export a simple function inside a file called function_module.js using this code

module.exports.squareFunction = function(nb){
return nb * nb ;
}

in other file in the same directory i tried to import the function using this code

const importedfun = require('./function_module.js');
console.log(importedfun(5));

i got this error

JavaScript\CodeAcademy\module\test_module.js:2
console.log(importedfun(5));
        ^

TypeError: importedfun is not a function
at Object.<anonymous>

can anyone tell me what is my fault ?

CodePudding user response:

By doing module.exports.squareFunction, you create a named export using commonjs syntax. You can either require it in another module using brackets {nameOfYourExportedFunction} or do a default export instead.

Named export

module.exports.squareFunction = function(nb){
    return nb * nb ;
}

//////

// Notice the brackets wrapping the function
const {squareFunction} = require('./function_module.js');
console.log(squareFunction(5));

Default export

module.exports = function(nb){
    return nb * nb ;
}

//////

// You can name it however you want since it will refer to the default export
const importedFun = require('./function_module.js');
console.log(importedfun(5));
  • Related