module.exports vs exports in Node.js

前端 未结 23 1728
自闭症患者
自闭症患者 2020-11-22 06:11

I\'ve found the following contract in a Node.js module:

module.exports = exports = nano = function database_module(cfg) {...}

I wonder what

23条回答
  •  Happy的楠姐
    2020-11-22 07:08

    To understand the differences, you have to first understand what Node.js does to every module during runtime. Node.js creates a wrapper function for every module:

     (function(exports, require, module, __filename, __dirname) {
    
     })()
    

    Notice the first param exports is an empty object, and the third param module is an object with many properties, and one of the properties is named exports. This is what exports comes from and what module.exports comes from. The former one is a variable object, and the latter one is a property of module object.

    Within the module, Node.js automatically does this thing at the beginning: module.exports = exports, and ultimately returns module.exports.

    So you can see that if you reassign some value to exports, it won't have any effect to module.exports. (Simply because exports points to another new object, but module.exports still holds the old exports)

    let exports = {};
    const module = {};
    module.exports = exports;
    
    exports = { a: 1 }
    console.log(module.exports) // {}
    

    But if you updates properties of exports, it will surely have effect on module.exports. Because they both point to the same object.

    let exports = {};
    const module = {};
    module.exports = exports;
    
    exports.a = 1;
    module.exports.b = 2;
    console.log(module.exports) // { a: 1, b: 2 }
    

    Also notice that if you reassign another value to module.exports, then it seems meaningless for exports updates. Every updates on exports is ignored because module.exports points to another object.

    let exports = {};
    const module = {};
    module.exports = exports;
    
    exports.a = 1;
    module.exports = {
      hello: () => console.log('hello')
    }
    console.log(module.exports) // { hello: () => console.log('hello')}
    

提交回复
热议问题