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){
        console.log("Retreiving from Cache");
        console.log("Executing " + name + " Module")
        var module = {"exports": {}};
        __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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.