Question

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;
    }
  }
};
Was it helpful?

Solution 2

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;
    }
  }
};

OTHER TIPS

If you came here (like me) because there is some modules you want to exclude from the bundle depending on a condition in your code, for example :

// I want browserify to ignore `nodeOnlyModule` because it
// can't be browserified (for example if it uses native extensions, etc ...)
var isBrowser = typeof window === 'undefined'
if (!isBrowser) var nodeOnlyModule = require('nodeOnlyModule')

There is different options (see the docs) :

  • browserify's ignore option will simply replace the module you don't want to bundle by an empty stub, and bundle that instead
  • exclude will exclude the module altogether, your code will then throw a "not found" error if you try to import it.
  • you can use the browser field from your package.json file. With this you can provide a mapping of files to import, in effect overriding node's module resolve algorithm when browserifying.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top