Search code examples
javascriptnode.jsrequire

What are the downsides of unnecessarily requiring the whole module.exports?


I only need to require one module (out of 6), but doing so would make the module I'm requiring less readable. For example, instead of doing this:

const { requestKrakenOrderbook } = require('./krakenUtils');
const orderbook = requestKrakenOrderbook();

I'd like to do this:

const krakenUtils = require('./krakenUtils')
const orderbook = krakenUtils.requestOrderbook()

What are the downsides of requiring the whole module like this?

What about this?

const getKrakenOrderbook = require('./krakenUtils').getOrderbook

Solution

  • There are no downsides. CommonJS modules are evaluated on require, entire module export is normally cached, so there's no significant difference in performance or memory footprint.

    Depending on what module exports are, it may be useful or not to store the entire module to a variable and use it as a namespace:

    const { get } = require('./foo');
    
    // 200 lines below
    let result = get(); // what in the world we've got?..
    

    vs.

    const foo = require('./foo');
    
    // 200 lines below
    let result = foo.get(); // ah, we've got foo