Skip to content

Instantly share code, notes, and snippets.

@benolee
Last active September 16, 2022 02:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benolee/7c10336f3a3303c0b289 to your computer and use it in GitHub Desktop.
Save benolee/7c10336f3a3303c0b289 to your computer and use it in GitHub Desktop.
bad javascript pipeline

Bad 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!

#!/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment