Search code examples
javascriptnode.jscommonjs

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?


Solution

  • 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.