Last active
August 2, 2024 18:23
-
-
Save paulodutra/84948e8c29203b5dcf37b63c73d39242 to your computer and use it in GitHub Desktop.
Ways of exports and imports modules using CommonJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
First way, object using module.exports | |
module.exports = { | |
sum: function(a,b){ | |
return a + b; | |
}, | |
sub: function(a,b){ | |
return a - b; | |
} | |
} | |
second way, only with name reference: | |
function sum(a,b) { | |
return a + b; | |
} | |
function sub(a,b) { | |
return a - b; | |
} | |
module.exports = { | |
sum, sub | |
} | |
Thrid, using object with exports.name: | |
exports.sum = function(a,b){ | |
return a + b; | |
} | |
exports.sub = function(a,b){ | |
return a - b; | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
First way, create a variable (const) and using variable.function or variavel.property | |
const myModule = require('./myModule'); | |
console.log(myModule.sum(1,1)); | |
Second way, using destructing to import specific functions and property: | |
const { sum } = require('./myModule'); | |
console.log(sum(1,1)); | |
Third way, import and handle the function in the same line. PS: It only works if the exports be a function. | |
const myModule = require('./myModule')(1,1); | |
console.log(myModule); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment