Skip to content

Instantly share code, notes, and snippets.

@ca0v
Last active January 19, 2022 14:06
Show Gist options
  • Save ca0v/20ff63360998ce843cf1a5579dc78042 to your computer and use it in GitHub Desktop.
Save ca0v/20ff63360998ce843cf1a5579dc78042 to your computer and use it in GitHub Desktop.
AMD RequireJS for ESM
const modules = <Record<string, any>>{};
function asAppPath(mid: string): string {
// depends on app, workaround for not supporting requirejs.config
if (mid.startsWith("app")) return `../../${mid}.js`;
return mid;
}
if (!globalThis.require) {
function define(mid: string, mod: any) {
modules[mid] = mod;
}
async function requirejs(mids: Array<string>, cb?: (...mods: Array<Function>) => void, err?: (message: any) => void) {
console.log({ mids });
const undefinedModules = mids.filter((k) => !modules[k]);
const validMids = undefinedModules.filter((m) => -1 === m.indexOf("!"));
try {
const newMods = await Promise.all(
validMids.map((mid) => {
try {
return import(/* @vite-ignore */ asAppPath(mid));
} catch (ex) {
throw error(`unable to load mid: ${mid}`);
}
})
);
// limit scope to default, all code assumes export = resource
// new code does not...so if no default return the entire namespace
validMids.forEach((key, i) => define(key, newMods[i].default || newMods[i]));
const finalMods = mids.map((k) => modules[k]);
// I can't recall how 'define' works :(
//.map((m) => (typeof m === "function" ? m() : m));
cb && cb(...finalMods);
} catch (ex) {
err && err(ex);
}
}
requirejs.toUrl = (a) => a;
requirejs.config = (a) => a;
Object.assign(globalThis, { requirejs, define });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment