Browserify:嵌套/有条件的需求

在下面的CommonJS / Browserify模块中,我怎样才能避免每次都导入foobar – 而只是在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; } } }; 

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

如果你来到这里(像我一样),因为有一些你想从包中排除的模块,这取决于代码中的条件,例如:

 // 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') 

有不同的选项(请参阅文档 ):

  • browserify的ignore选项将简单地replace您不想捆绑的模块,并将其捆绑
  • exclude将完全排除模块,如果您尝试导入它,则代码将抛出“找不到”错误。
  • 您可以使用package.json文件中的browser字段。 有了这个,你可以提供一个导入文件的映射,实际上在浏览时覆盖节点的模块parsingalgorithm。