CommonJS `require` via Sync XHR

A simplified implementation of the CommonJS module system (`require` and friends) for the browser using synchronous XMLHttpRequests and `eval`. This does NOT support dynamically "finding" modules as that could incur a whole bunch of 404s. Currently also configured only to work on the same domain but could be configured to work cross-domain with CORS support.

by James Greene

JavaScript

(function () {

    function getUriDir(uri) {
        return !uri ? "" : (uri = uri.split("#")[0].split("?")[0]).slice(0, uri.lastIndexOf("/") + 1);
    }

    function getDocumentBaseURI() {
        var tmp,
        baseURI = getUriDir(document.baseURI);
        if (!baseURI && (tmp = document.getElementsByTagName("base")).length && (tmp = tmp[0].href)) {
            baseURI = getUriDir(tmp);
        }
        return baseURI || getUriDir(window.location.href);
    }

    var __baseURI__ = getDocumentBaseURI();
    var __origin__ = __baseURI__.slice(0, 8).toLowerCase() === "file:///" ?
        "file://localhost/" : __baseURI__.slice(0, __baseURI__.indexOf("/", __baseURI__.indexOf("://") + 3));


    function arrayIndexOf(arr, item) {
        if (arr && arr.length) {
            if (arr.indexOf) {
                return arr.indexOf(item);
            }
            // else...
            for (var i = 0, len = arr.length; i < len; i++) {
                if (arr[i] === item) {
                    return i;
                }
            }
        }
        return -1;
    }

    function dirname(path) {
        return (path && path.slice(0, path.lastIndexOf("/") + 1)) || "/";
    }

    function getModuleSync(resolvedPath) {
        var req = new XMLHttpRequest();
        req.open('GET', __origin__ + resolvedPath, false);
        req.send(null);

        if (req.status >= 200 && req.status < 400) {
            return req.responseText;
        }
        throw new Error("Module not found! URI: " + resolvedUri);
    }

    function isNotPlainObject(obj) {
        var plainObj = {};
        for (var prop in obj) {
            if (obj.hasOwnProperty(prop) && !plainObj.hasOwnProperty(prop)) {
                return true;
            }
        }
        return false;
    }

    function evaluateModule(__dirname, __filename, __parentModule__, __moduleScriptText__) {
        var module = {
            exports: {},
            id: __filename,
            filename: __filename,
  ...