This script is the result of playing with the tiny module loader used in the build process of ember.js, and the rake-pipeline filter for minispade.
This isn't meant for anything but helping to understand how they work! Don't use this terrible build script in your project!
This script assumes you have a file named lib/main.js
. You can use the requireModule
function to make sure that other scripts are loaded first. All scripts are evaluated in the global context. Each script/module is only loaded once regardless of how many times it's required. Only scripts in lib
will be included in the compiled output.
Assuming you have lib/main.js
, lib/core.js
, and lib/util.js
, that have the following contents:
// lib/main.js
requireModule('lib/core.js');
requireModule('lib/util.js');
// lib/core.js
console.log('-----> lib/core.js required');
// lib/util.js
requireModule('lib/core.js');
console.log('-----> lib/util.js required');
you can build the compiled output like this:
bash build.bash
which results in
(function() {
var define, requireModule;
(function() {
var registry = {}, seen = {};
define = function(name, callback) {
registry[name] = callback;
};
requireModule = function(name) {
if (seen[name]) return;
seen[name] = true;
registry[name]();
};
})();
define('lib/core.js', function() {
// lib/core.js
console.log('-----> lib/core.js required');
});
define('lib/main.js', function() {
// lib/main.js
requireModule('lib/core.js');
requireModule('lib/util.js');
});
define('lib/util.js', function() {
// lib/util.js
requireModule('lib/core.js');
console.log('-----> lib/util.js required');
});
requireModule('lib/main.js');
})();
running this in a browser results in the following console logs:
-----> lib/core.js required
-----> lib/util.js required
Have fun!