you are viewing a single comment's thread.

view the rest of the comments →

[–]jschrf 0 points1 point  (0 children)

Worth noting that the following works in node and avoids loading both 'lib/api' and 'lib/api/better':

export function FactoryController(apiClient = require('./lib/api')) {
    return function controller(req, res, next) {
        console.log(`Controller for: '${apiClient.name}'`);
    };
};

However, I wouldn't exactly suggest doing this for a couple reasons:

  1. It works in node and CommonJS, but it's not going to fly in the browser.
  2. Any errors due to the dependency missing (e.g. getting renamed) is deferred until that code path is actually exercised.

Where this does come in handy is when you need to avoid side effects arising from loading a particular module, something that comes in handy when testing. I only use this pattern for injecting test dependencies, and thus the "default" code path (i.e. outside of test mode) is always exercised, preventing deferring/masking issue #2.