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

解决方法

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

相关文章

什么是深拷贝与浅拷贝?深拷贝与浅拷贝是js中处理对象或数据...
前言 今天复习了一些前端算法题,写到一两道比较有意思的题:...
最近在看回JavaScript的面试题,this 指向问题是入坑前端必须...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面