Browserify:嵌套/条件要求

can*_*era 10 javascript commonjs node.js 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;
    }
  }
};
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)

有不同的选择(参见文档):

  • browserify的ignore选项将简单地替换您不想通过空存根捆绑的模块,而是将其捆绑
  • exclude 将完全排除该模块,如果您尝试导入它,您的代码将抛出"未找到"错误.
  • 您可以使用文件中的browser字段package.json.通过这种方式,您可以提供要导入的文件的映射,实际上在浏览时覆盖节点的模块解析算法.


vku*_*kin 5

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)

  • 这实际上是否避免导入这两个文件?我很确定当Browserify内联`require()`语句时,它会捆绑所有内容,无论它是否在条件中,但我可能是错的. (9认同)
  • 当然它会捆绑所有东西,在编译时无法知道结果 (8认同)