Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Browserify: Nested/Conditional Requires

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;
    }
  }
};
like image 461
cantera Avatar asked Apr 23 '14 16:04

cantera


2 Answers

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.
like image 91
sebpiq Avatar answered Sep 23 '22 10:09

sebpiq


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;
    }
  }
};
like image 24
vkurchatkin Avatar answered Sep 22 '22 10:09

vkurchatkin