Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the bundle order work in browserify?

I cannot figure out the logic for how browserify bundles its required files. If I do this

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

The output is this

(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])

As you can see, 'three' is bundle before 'two' but thats not the order I required them in?

like image 944
user2808895 Avatar asked Apr 23 '14 08:04

user2808895


1 Answers

Looks like it’s alphabetical. Maybe Browserify sorts them that way or that’s just how it comes from the OS. It doesn’t really make any difference—those are just the module definitions. Your code, inside those (require, module, exports) functions, will always run the same no matter what order the modules were defined in.

Here’s a simplified version of what Browserify is doing that may be more clear:

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

Even if you change the order the modules are defined you should always see the same output:

one
two
three
like image 154
Todd Yandell Avatar answered Oct 24 '22 11:10

Todd Yandell