简体   繁体   中英

How To Use Module Exports Properly In JavaScript

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?

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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