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;
}
}
};
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;
}
}
};
Share
Improve this question
asked Apr 23, 2014 at 16:09
canteracantera
25k25 gold badges102 silver badges140 bronze badges
2 Answers
Reset to default 13If 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 yourpackage.json
file. With this you can provide a mapping of files to import, in effect overriding node's module resolve algorithm when browserifying.
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;
}
}
};