Search code examples
javascriptnode.jscommonjs

Assigning value to module.exports


I am reading about module.exports in Node.js Design Patterns. In this book, it is mentioned that:

Reassigning the exports variable doesn't have any effect, because it doesn't change the contents of module.exports, it will only reassign the variable itself.

The following code is therefore wrong:

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

I am not able to understand why the above assignment is wrong?


Solution

  • You are overwriting the local exports variable by doing this. Which is local to the wrapper function around each Node.js file. There is no way for V8 to know what modification you made to the original exports object as you are using a new object.

    What you want to do is overwrite the exports key in the module object.

    module.exports = function() {
      console.log('Hello');
    };
    

    For more convenience you could also assign to the exports variable so that you can leverage it locally: module.exports = exports = .... That really what exports is, a faster way to access module.exports.