Question
If module.exports
is assigned an object, either by a variable name or an object literal, does it have access to variables defined outside of module.exports
within the same file?
Answer
The object being assigned to module.exports
will have access to other variables that are defined within the same scope, however if those other variables are not also being exported, we will not have access to them in the file importing the module.
For example:
moduleToExport.js:
const myVar = {
prop1: 'prop 1'
}
const objToExport = {
key1: myVar.prop1
}
module.exports = objToExport;
main.js:
const myModule = require('./moduleToExport.js'); //require the exported module which is the objToExport object
console.log(myModule); //logs the object `{ key1: 'prop 1' }` to the console, which does not include a reference to the variable myVar