<div id='log'></div>
const myCode1 = `
  let utils = function (){
    this.say = function(x){
      log('utils: says = ' + x)
      };
      return this;
  }
  exports.utils = utils;
`;
const myCode2 = `
  let customer = function (){
    this.say = function(x){
      log('Customer: says = ' + x)
      };
      return this;
  }
  exports.customer = customer;
`;
/*

*/  
// I am loading simple source code strings into an array - in the real solution
// you would use some kind of source code fetch / load to string process.
let sourceCode = {c1: myCode1, c2: myCode2};
myRequire.cache = Object.create(null); 

function myRequire(name) {   
    log(`myRequire: You require file ${name}`)
    if (!(name in myRequire.cache)) {
        log(`myRequire: ${name} is not in cache; reading from disk`)
        let code = sourceCode[name]; // load the code - this is bespoke to your env      
        let module = {exports: {}};
        myRequire.cache[name] = module;     
        let wrapper = Function("require, exports, module", code);     
        wrapper(myRequire, module.exports, module);
    }
    log(`myRequire: ${name} is in cache. Returning it...`)
    return myRequire.cache[name].exports;
}

// myRequire() produces an object from the 'exports' object in the loaded code.
//let myExports = new myRequire('c1');
// we can then refer to these as 
// let util = myExports.utils();
// or just use 
// let util = new myRequire('c1').utils();

// So...Require c1 will create an object with exports.
let util = new myRequire('c1').utils();
util.say('I am alive!')
 
log("");

// Require c2 will create an object with exports.
let cust = new myRequire('c2').customer();
cust.say('I am alive too!')

function log(msg){
  $('#log').html($('#log').html() + "<br />" + msg);
}
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js