modulejs

lightweight JavaScript module system

Advertisement
0.2

modulejs is a lightweight JavaScript module system. It is not a module loader, it triggers no file system lookups or HTTP requests. It simply helps organizing code in small, maintainable and easy to use modules. Modules respect and resolve dependencies, the syntax is very similar to that of RequireJS. This is the module system used in h5ai.

The sources and a changelog are available on GitHub.

Usage

Define a module without dependencies.

modulejs.define('foo', function () {
 
	// module setup code and definitions
 
	return some_foo_object;
});

Define a module with dependencies.

modulejs.define('bar', ['foo'], function (foo) {
 
	// module setup code and definitions
 
	return some_bar_object;
});

Define another module.

modulejs.define('main', ['jquery', 'bar', 'modernizr', 'foo'], function ($, bar, mod, foo) {
 
	// module setup code and definitions
 
	return main_object;
});

It's easy to register 3rd party objects.

modulejs.define('modernizr', Modernizr);

But you need to be careful with 'objects' that actually are functions.

modulejs.define('jquery', function () {
 
	return jQuery;
});

Finally for example at "document.ready" require one of the defined modules and run some code.

$(function () {
 
	var app = module.require('main');
	app.start();
});

API

define

Defines a module through a constructor function. This function will only be called once when module is first required. The return value will be stored and returned whenever this module will be required.

modulejs.define(id: String, constructor: Function ): undefined

Same as above but with dependencies that get resolved first and will be passed in as arguments to the constructor.

modulejs.define(id: String, dependencies: [String, ...], constructor: Function ): undefined

Defines a module through an already existing object that gets returned whenever the module is required.

modulejs.define(id: String, object: Object ): undefined

Same as above but with dependencies that get resolved first.

modulejs.define(id: String, dependencies: [String, ...], object: Object ): undefined

require

Returns an already defined module. Creates it if necessary.

modulejs.require(id: String): Object

state

Returns an object that represents the current state of all modules.

modulejs.state(): Object

log

Returns a string representing module dependencies in a easy to read format. If invert is true it shows dependents for each module.

modulejs.log([invert: Boolean]): String

License

modulejs is provided under the terms of the MIT License.