I know that "exports" and "module.exports" are functionally identical.
But I found that when they actually run under the same conditions, they produce different results.
I found this difference applying the internal module pattern to my project.
Below is a brief example code for situations in which differences have occurred.
modules.js ("exports" Ver)
const calsum = require("./calsum"),
calculator = require("./calculator");
exports.calsum = calsum; // this is "exports" Ver
exports.calculator = calculator; // this is "exports" Ver
Only the 4th and 5th lines of the modules.js will be changed and the other js files are all under the same conditions. "exports" is used in this modules.js
modules.js ("exports.module" Ver)
const calsum = require("./calsum"),
calculator = require("./calculator");
exports.modules = {calsum, calculator}; // this is "export.modules" Ver
"exports.module" is used in this modules.js
calsum.js
function sumit(a,b) {
return a + b;
}
module.exports = {sumit};
calculator.js
const modules = require("./modules");
class Calculator {
constructor() {}
calSum(a,b) {
let total = modules.calsum.sumit(a,b);
return total;
}
}
module.exports = {Calculator}
index.js
const modules = require("./modules"); // modules = { 'calsum' : sumit(function), 'calculator' : Calculator(obj) }
let myObj = new modules.calculator.Calculator();
console.log(myObj.calSum(2,4));
When I run index.js, the one using "exports" works correctly.
But using "module.exports" causes TypeError.
I just guess that when myObj.calSum(2,4) was called in and entered the scope, the modules property could not be loaded properly.
I don't know why.
It must be the same code functionally, but why does this difference occur?
I couldn't find an answer even after thinking for a long time.
I want you to share your knowledge with me.