can*_*era 10 javascript commonjs node.js browserify
在下面的CommonJS的/ Browserify模块,我怎样才能避免导入既foo与bar每一次-而不是导入仅仅是基于条件所需要的一个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;
}
}
};
Run Code Online (Sandbox Code Playgroud)
seb*_*piq 12
如果您来到这里(像我一样),因为根据代码中的条件,您希望从捆绑中排除某些模块,例如:
// 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')
Run Code Online (Sandbox Code Playgroud)
有不同的选择(参见文档):
ignore选项将简单地替换您不想通过空存根捆绑的模块,而是将其捆绑exclude 将完全排除该模块,如果您尝试导入它,您的代码将抛出"未找到"错误.browser字段package.json.通过这种方式,您可以提供要导入的文件的映射,实际上在浏览时覆盖节点的模块解析算法.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;
}
}
};
Run Code Online (Sandbox Code Playgroud)