捆绑订单如何在browserify中运行?

时间:2014-04-23 08:50:56

标签: javascript browserify

我无法弄清楚browserify如何捆绑其所需文件的逻辑。如果我这样做

require('./one/one.js');
require('./two/two.js');
require('./three/three.js');

输出就是这个

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var app = "app";

console.log(one);
},{}],2:[function(require,module,exports){
require('./one/one.js');
require('./two/two.js');
require('./three/three.js');
//require('./three/three_a/three_a.js');
require('./app.js');
},{"./app.js":1,"./one/one.js":3,"./three/three.js":4,"./two/two.js":5}],3:[function(require,module,exports){
var one = "one";
},{}],4:[function(require,module,exports){
var three = "three";
},{}],5:[function(require,module,exports){
var two = "two";
},{}]},{},[2])

正如你所看到的,“三个”在“两个”之前是捆绑的,但那不是我要求它们的顺序吗?

1 个答案:

答案 0 :(得分:7)

看起来像是按字母顺序排列的。也许Browserify以这种方式对它们进行排序,或者就是它来自操作系统的方式。它没有任何区别 - 这些只是模块定义。无论模块的定义顺序如何,在(require, module, exports)函数内的代码总是运行相同的。

以下是Browserify所做的简化版本,可能更清晰:

var modules = {
  './app.js': function (require, module, exports) {
    require('./one/one.js');
    require('./two/two.js');
    require('./three/three.js');
  },
  './two/two.js': function (require, module, exports) {
    console.log('two');
  },
  './one/one.js': function (require, module, exports) {
    console.log('one');
  },
  './three/three.js': function (require, module, exports) {
    console.log('three');
  }
};

function require (path) {
  var module = {exports: {}};
  modules[path](require, module, module.exports);
  return module.exports;
}

require('./app.js');

即使您更改了模块的定义,您也应该始终看到相同的输出:

one
two
three