secret
Last active

ghetto javascript pipeline

  • Download Gist
README.md
Markdown

Ghetto JavaScript Pipeline

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!

General

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.

Usage

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!

build.bash
Shell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#!/usr/bin/env bash
 
cat <<EOF
(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]();
};
})();
 
EOF
 
for file in lib/*.js; do
cat <<EOF
define('${file}', function() {
$(cat $file)
});
EOF
done
 
cat <<EOF
requireModule('lib/main.js');
})();
EOF

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.