Building runtime tree of Angular modules

See what each loaded Angular module provides and how it links to its dependencies.

We can see in real time the modules and what they provide for any given Angular application.

Once an application has been bootstrapped, we can fetch any Angular module using angular.module function

(function app() {
    angular.module('foo', ['bar'])
        .value('lifeMeaning', 42);
}());
var m = angular.module('foo');
// inspect object m

We can see all modules that foo requires to run

console.log('module', m.name, 'requires', m.requires);
// module foo requires ['bar']

This information allows us to reconstruct a tree of modules and their connections, for example we can create a node for each module, and link every required node as a child, forming a graph (hopefully acyclical).

What about values, constants, services, controllers, directives and other features that each module can provide? How can we list those for each module? Under the hood, everything a module provides is implemented using $provide service. Thus module foo provides value lifeMeaning. If we inspect m._invokeQueue list, we can see everything a module provides. In this case, it has a single entry

console.log(angular.module('foo')._invokeQueue);
[ ['$provide', 'value', ['lifeMeaning', 42] ] ]

Directives, controllers, factories - everything has similar item in the _invokeQueue.

I have writte ng-ast to extract these names and build a syntax tree from a given root module.

1
2
3
4
5
6
7
8
9
10
var root = ngAst('foo');
// root is
{
name: 'foo',
values: 'lifeMeaning'
dependencies: ['bar'], // just string names
services: [],
factories: [],
children: [ // node for module 'bar' ]
}

We can easily walk the entire tree using children list.