Organize Loading JS Modules in Browserify Apps
Organize Loading JS Modules in Browserify Apps
Advertisement

Browserify has to be able to statically analyze all of the require statements at build time so it can know what files it needs to include in the bundle. That requires that require can only be used with a string literal in the source code. To organize loading js modules, there are many ways to do that.

By the way, Browserify is a development tool that allows us to write node.js-style modules that compile for use in the browser. Just like node, we write our modules in separate files, exporting external methods and properties using the module.exports and exports variables.

Organize Loading JS Modules in Browserify Apps

My way is to make a lazy module loader which returns one object of modules that are needed to be instantiated one time only (Singleton Objects). This loader can be accessed in the global scope and it is very easy to use.

Modules Loader

Let’s assume that you have written two separated modules named LightComposer.js and TextTranslator.js. These two modules are needed in many contexts in the app and you don’t want to require them every time. Therefore, you can write the following loader module to load them in one place.

var ML = {
    objects: [],
    //get instance
    gI: function (objectClassName) {
            try {
                if (!this.objects[objectClassName])
                {
                    switch (objectClassName)
                    {
                        case 'LightComposer':
                            this.objects[objectClassName] = require('./LightComposer.js');
                            break;
		        case 'TextTranslator':
			    this.objects[objectClassName] = require('./TextTranslator.js');
			    break;
                    }
                }
                return this.objects[objectClassName];

            } catch (err)
            {
                throw new Error(err);
                return;
            }
    }
}
module.exports = ML;

Name this module ML.js and require it in the main.js to be bundled by Browserify. Assign the module to a variable in the global scope.

global.ML = require('./ModulesLoader.js');

Now, this module is available anywhere in your application and can give you the needed modules anytime you want by doing like below

ML.gI('LightComposer').doSomethingNow();

This simple module loader makes your app consume less memory and perform faster. So go ahead and try it!

The code is available via GitHub

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.