# Bundling JavaScript modules into a single file

I was just going through Modular Design Patterns in JavaScript and I came across bundlers like browserify and webpack. They solve an interesting problem of combining all dependencies into a monolithic file.

I was interested to see how I can flatten out multiple files say main.js, utils.js, core.js written in commonJSish format that uses require to load other modules which might recursively require other modules.

Can someone review this and give me some drawbacks and suggestions? It is commonJSish because it doesn't support export yet.

Currently, we are using the absolute path as the key. So a consumer has to write the absolute path. One solution would be to allow users to write relative path in the code and the bundler taking care of changing it to absolute paths.

// Goal: How to bundle multiple modules into a single file written in
// commonJSish syntax?

// Premise: I am trying to understand the "browserify" code. So I had to
// try something myself ...

// This is the core which provides "require".

__cache__ = {}

function require(name){
if(__cache__[name]){
console.log("Retreiving from Cache");
}
else{
console.log("Executing " + name + " Module")
var module = {"exports": {}};
map[name](module);
__cache__[name] = module.exports;
}
return __cache__[name];
}

map = {}

// This is the module code. A parser can be used to generate this.

// 1. Each of these is a real file in the filesystem.
// 2. The function wrapper doesn't exist in the real file.
// 3. The order doesn't matter.

map['main.js'] = function(module) {
var utils = require("utils.js");
var core = require("core.js")
module.exports.name = "main.js";
module.exports.dependencies = [utils, core];
};

map['utils.js'] = function(module) {
module.exports.name = "utils.js"
};

map['core.js'] = function(module) {
module.exports.name = "core.js"
};

// The entry is just a "require" call.

require("main.js");

• #1 issue: __cache__ and map are global. – Gerrit0 Dec 25 '17 at 21:21
• github.com/browserify/browser-pack/blob/… seems close. But I need to see it more closely. – Nishant Dec 26 '17 at 7:52