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;
}
}
};
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) :
ignore
option will simply replace the module you don't want to bundle by an empty stub, and bundle that insteadexclude
will exclude the module altogether, your code will then throw a "not found" error if you try to import it.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.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;
}
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With