module.exports vs exports in Node.js

前端 未结 23 1294
自闭症患者
自闭症患者 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 07:08

    why both are used here

    I believe they just want to be clear that module.exports, exports, and nano point to the same function - allowing you to use either variable to call the function within the file. nano provides some context to what the function does.

    exports won't be exported (only module.exports will), so why bother overwriting that as well?

    The verbosity trade-off limits the risk of future bugs, such as using exports instead of module.exports within the file. It also provides clarification that module.exports and exports are in fact pointing to the same value.


    module.exports vs exports

    As long as you don't reassign module.exports or exports (and instead add values to the object they both refer to), you won't have any issues and can safely use exports to be more concise.

    When assigning either to a non-object, they are now pointing to different places which can be confusing unless you intentionally want module.exports to be something specific (such as a function).

    Setting exports to a non-object doesn't make much sense as you'll have to set module.exports = exports at the end to be able to use it in other files.

    let module = { exports: {} };
    let exports = module.exports;
    
    exports.msg = 'hi';
    console.log(module.exports === exports); // true
    
    exports = 'yo';
    console.log(module.exports === exports); // false
    
    exports = module.exports;
    console.log(module.exports === exports); // true
    
    module.exports = 'hello';
    console.log(module.exports === exports); // false
    
    module.exports = exports;
    console.log(module.exports === exports); // true
    

    Why assign module.exports to a function?

    More concise! Compare how much shorter the 2nd example is:

    helloWorld1.js: module.exports.hello = () => console.log('hello world');

    app1.js: let sayHello = require('./helloWorld1'); sayHello.hello; // hello world

    helloWorld2.js: module.exports = () => console.log('hello world');

    app2.js: let sayHello = require('./helloWorld2'); sayHello; // hello world

提交回复
热议问题