Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Browserify:嵌套/条件化_Javascript_Node.js_Commonjs_Browserify - Fatal编程技术网

Javascript Browserify:嵌套/条件化

Javascript Browserify:嵌套/条件化,javascript,node.js,commonjs,browserify,Javascript,Node.js,Commonjs,Browserify,在下面的CommonJS/Browserify模块中,如何避免每次都导入foo和bar——而不是只导入基于init()中的条件所需的一个 如果您(像我一样)来到这里,是因为您想根据代码中的条件从捆绑包中排除一些模块,例如: // I want browserify to ignore `nodeOnlyModule` because it // can't be browserified (for example if it uses native extensions, etc ...) va

在下面的CommonJS/Browserify模块中,如何避免每次都导入
foo
bar
——而不是只导入基于
init()中的条件所需的一个

如果您(像我一样)来到这里,是因为您想根据代码中的条件从捆绑包中排除一些模块,例如:

// 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
    选项将简单地用一个空存根替换您不想绑定的模块,并将其绑定
  • exclude
    将完全排除该模块,如果您尝试导入该模块,则代码将抛出“未找到”错误
  • 您可以使用
    package.json
    文件中的
    browser
    字段。有了它,您可以提供要导入的文件的映射,实际上在浏览时覆盖节点的模块解析算法

这实际上是否避免了导入这两个文件?我很确定,当Browserify内联
require()
语句时,它会将所有内容捆绑起来,不管它是否在条件中,但我可能错了。当然,它会将所有内容捆绑起来,在编译时无法知道您可能要查找的结果
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')