【问题标题】:Browserify: Nested/Conditional RequiresBrowserify:嵌套/条件需求
【发布时间】:2014-06-08 14:42:00
【问题描述】:

在下面的 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;
    }
  }
};

【问题讨论】:

    标签: javascript node.js commonjs browserify


    【解决方案1】:

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

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

    有不同的选择(见the docs):

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

    【讨论】:

      【解决方案2】:
      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;
          }
        }
      };
      

      【讨论】:

      • 这实际上避免了导入这两个文件吗?我很确定当 Browserify 内联 require() 语句时,它会捆绑所有内容,无论它是否处于条件状态,但我可能错了。
      • 当然会捆绑一切,编译时无法知道结果
      猜你喜欢
      • 2017-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-30
      • 1970-01-01
      • 1970-01-01
      • 2015-03-12
      • 2015-01-28
      相关资源
      最近更新 更多