Skip to content

Instantly share code, notes, and snippets.

@paulodutra
Last active August 2, 2024 18:23
Show Gist options
  • Save paulodutra/84948e8c29203b5dcf37b63c73d39242 to your computer and use it in GitHub Desktop.
Save paulodutra/84948e8c29203b5dcf37b63c73d39242 to your computer and use it in GitHub Desktop.
Ways of exports and imports modules using CommonJS
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;
}
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