Philippe Hebert Philippe Hebert - 5 months ago 30
AngularJS Question

AngularJS Module Declaration Order

I have been experiencing an inconsistent behaviour regarding the module declaration order for AngularJS apps. On my current machine, both of the following orders of module declaration work, while on my colleague's machine, only the second ordering compiles without dependency errors.

First Order [Breath First]

Here modules are declared in a breath first fashion, aka the parent module are declared, and then the dependencies are declared subsequently below. This way of declaring module is reminiscent of the way Python modules are loaded by the interpretor, or of how Java classes load their imports.

(function() {
angular.module('app.services', [
'app.services.data',
'app.services.nav',
'app.services.session'
]);
})();

(function(){
angular.module("app.services.data", []);
})();


Second Order [Depth First]

Here modules are declared in a depth first fashion, putting dependencies that are deeper in the dependency tree earlier in the file so that these sub dependencies are already declared when they are loaded as dependencies for a higher level module. This way is typical of JavaScript variable ordering declaration. Variable A cannot use B before it is declared.

(function(){
angular.module("app.services.data", []);
})();

(function() {
angular.module('app.services', [
'app.services.data',
'app.services.nav',
'app.services.session'
]);
})();


So now my question is: Why is this behaviour different from machine to machine? My current machine is under Ubuntu 14.04 64bits with an Intel Core i5-3230M processor and my browser is Chrome 51.03, while my colleague's machine is a Windows 10 machine with an Intel Core i5-4570k and Chrome 51.03 as his browser. We are both using the same source code, the same compilation script (gulp) and the same dependencies (angular ^1.5.0).

Bonus points if you also have an idea how I can ensure proper dependency order in my gulpfile without having to manually order them one by one.

Answer

JS modules can maintain proper file loading order automatically. If 'compilation script' is just Gulp concat, it makes this a challenge and requires to specify file order explicitly.

If files are loaded in alphabetic order, this won't work. I would suggest to stick to proper tools (Webpack/Browserify) for that. JS modules don't substitute Angular modules but compliment them.

And the problem cease to exist even for concatenated build if the app is extremely modular (one module per each file/unit) and angular.module('...') is banned from use. This approach is highly beneficial with OOP design and 'one class per file' convention.

Comments