Sunday, September 24, 2006

The perfect javascript dependency mechanism

I plan to find out whether a good dynamic dependency system exists for javascript or not, but first I'd like to sketch my thoughts on what an ideal solution might look like.

Module Declarations
Dependencies will be exposed at the level of modules - this is an arbitrary sized collection of objects. It could be one function, one class, a group of function or a group of classes.
Modules will be declared like:

function (){
var moduleHandle = initialiseModule("my.module.namespace");
var namespace = {};
namespace.some_func = function(){
// delcaration of module
registerModule(moduleHandle, namespace);
}();

Dependency Registration
Modules will have to first register their dependencies (so that they can be loaded before they are needed) . Wildcards should be allowed for ease of use (and to encourage small modules).

registerDependency(moduleHandle, "some.module.namespace");
registerDependency(moduleHandle, "some.library.*");


Dependency Exposure
Secondly we have to expose the dependencies, ideally this needs to be done in the minimum possible scope to avoid scope contamination.

namespace.someFunc = function(){
var $ = exposeDependency("some.library.$");
}


Package Registration
To make this work the system will need to know which files satisfy which dependency. This will be achieved with a simple package declaration (probably stored in a package file)

registerPackage("some.library.*", "path/to/file.js");

Static Analysis
The ideal solution would also enable some kind of static dependency analysis by outputing some kind of dependency graph.