Skip to content

Instantly share code, notes, and snippets.

@arturovt
Last active March 20, 2019 21:26
Show Gist options
  • Save arturovt/aa71672b568bbaee561cfd22fe8b8ef3 to your computer and use it in GitHub Desktop.
Save arturovt/aa71672b568bbaee561cfd22fe8b8ef3 to your computer and use it in GitHub Desktop.
const cache: {
[key: string]: any;
} = {};
function getModuleCode(path: string): Promise<string> {
return fetch(path).then((res) => res.text());
}
async function import<T = unknown>(path: string): Promise<T> {
if (cache.hasOwnProperty(path)) {
return cache[path];
}
const code = await getModuleCode(path);
const module = cache[path] = {
exports: {} as T
};
Function('module, exports', code)(module, module.exports);
return module.exports;
}
(async () => {
const value = await import<number>('./value.js'); // 42
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment