direktspeed / esm-loader

Offers Cross Environment Context ESM Loading even from Strings is a Loader Construction Framework for Userland http import in nodejs supports remote url including node-resolve via rollup
Apache License 2.0
6 stars 2 forks source link

First version of a require browser implementation. #9

Open frank-dspeed opened 4 years ago

frank-dspeed commented 4 years ago
async function require(path) {
    let _module = window.module;
    window.module = {};
    await import(path);
    let exports = module.exports;
    window.module = _module; // restore global
    return exports;
}

(async () => { // top-level await cannot come soon enough…

let x = await require("https://cdn.jsdelivr.net/gh/x/lib/index.js");

})();
frank-dspeed commented 4 years ago
// We need a separate import to run code before the UMD module evaluates
import './my-module-setup.js';

// load the UMD module, which will populate window.exports
import './my-module.umd.js';

//export the UMD exports
export default let exports = window.exports;

// cleanup
window.exports = undefined;

Custom Shim The custom shim works the same, but uses individual exports. This would likely be generated:

my-module.js:

// We need a separate import to run code before the UMD module evaluates
import './my-module-setup.js';

// load the UMD module, which will populate window.exports
import './my-module.umd.js';

//export the UMD exports
export const a = window.exports.a;
export const b = window.exports.b;

// cleanup
window.exports = undefined;

ideas from umd