module.exports vs exports in Node.js

前端 未结 23 1723
自闭症患者
自闭症患者 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条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 06:57

    module.exports and exports both point to the same object before the module is evaluated.

    Any property you add to the module.exports object will be available when your module is used in another module using require statement. exports is a shortcut made available for the same thing. For instance:

    module.exports.add = (a, b) => a+b
    

    is equivalent to writing:

    exports.add = (a, b) => a+b
    

    So it is okay as long as you do not assign a new value to exports variable. When you do something like this:

    exports = (a, b) => a+b 
    

    as you are assigning a new value to exports it no longer has reference to the exported object and thus will remain local to your module.

    If you are planning to assign a new value to module.exports rather than adding new properties to the initial object made available, you should probably consider doing as given below:

    module.exports = exports = (a, b) => a+b
    

    Node.js website has a very good explanation of this.

提交回复
热议问题