tetrissimo/requirejs-polyfill.js
2021-06-07 10:42:00 -07:00

53 lines
1.2 KiB
JavaScript

((window) => {
const moduleCache = {};
const exportsCache = {};
const exportsPlaceholder = '!exports';
function define(name, deps, fn) {
if (Array.isArray(name)) {
if (typeof (deps) === 'function') {
const resolvedDeps = require(name);
deps.apply(null, resolvedDeps);
}
return;
}
moduleCache[name] = {deps, fn};
}
function require(names) {
return (names || [])
.map((name) => {
if (name in exportsCache) {
return exportsCache[name];
}
if (name === 'exports') {
return exportsPlaceholder;
}
const mod = moduleCache[name];
if (!mod) {
throw new Error(`Unknown module "${name}"`);
}
exportsCache[name] = {};
const args = require(mod.deps);
const index = args.findIndex(x => x === exportsPlaceholder);
if (index !== -1) {
args[index] = exportsCache[name];
}
mod.fn.apply(null, args);
const moduleKey = '__$module';
if (exportsCache[name][moduleKey]) {
exportsCache[name] = exportsCache[name][moduleKey];
}
return exportsCache[name];
});
}
window.require = exportsCache.require = require;
window.define = define;
window.exportsCache = exportsCache;
window.moduleCache = moduleCache;
})(window);