module.exports vs exports in Node.js

前端 未结 23 1248
自闭症患者
自闭症患者 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:53

    exports and module.exports are the same unless you reassign exports within your module.

    The easiest way to think about it, is to think that this line is implicitly at the top of every module.

    var exports = module.exports = {};
    

    If, within your module, you reassign exports, then you reassign it within your module and it no longer equals module.exports. This is why, if you want to export a function, you must do:

    module.exports = function() { ... }
    

    If you simply assigned your function() { ... } to exports, you would be reassigning exports to no longer point to module.exports.

    If you don't want to refer to your function by module.exports every time, you can do:

    module.exports = exports = function() { ... }
    

    Notice that module.exports is the left most argument.

    Attaching properties to exports is not the same since you are not reassigning it. That is why this works

    exports.foo = function() { ... }
    

提交回复
热议问题