Maximus - 8 months ago 48
Javascript Question

# Why doesn't the following exports = { z: function() {} }; work

a.js

exports = {
z: function() {
console.log('aZ');
}
};


main.js

require('./a').z(); // error


Why does
require('./a')
return an empty object?

Because in your example you are overriding the exports global, and not updating it. If you replace your code with:

exports.z = function() {
console.log('aZ');
};


it will work, because you are adding z to the actual exports object.

If you look at the docs, you will see:

A reference to the module.exports that is shorter to type.

So you can imagine this situation:

var module = {
exports: { /* some export stuff */ }
};

var exports = module.exports;


Now if you replace exports with exports = something, you aren't actually changing module.exports.