Browserify: Nested/Conditional Requires

browserify, commonjs, javascript, node.js

Solution

Component = function(config) {
  this.type = config.type;
  this.init();
};

Component.prototype = {

  init: function() {
    var instance = null;

    switch (this.type) {
      case ('foo'):
        instance = new (require('foo'))(...);
        break;
      case ('bar'):
        instance = new (require('bar'))(...);
        break;
    }
  }
};

Problem

In the CommonJS/Browserify module below, how can I avoid importing both `foo` and `bar` every time -- instead importing only the one that is needed based on the conditional in `init()`? ``` var Foo = require('foo'), Bar = require('bar'), Component = function(config) { this.type = config.type; this.init(); }; Component.prototype = { init: function() { var instance = null; switch (this.type) { case ('foo'): instance = new Foo(...); break; case ('bar'): instance = new Bar(...); break; } } }; ```

Original source