11

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

2 Answers 2

13

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.
Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

Does this actually avoid importing both files though? I'm pretty sure that when Browserify inlines the require() statements it will bundle up everything, regardless of whether it's in a conditional, but I may be wrong.
of course it will bundle up everything, there is no way to know the result at compile time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.