Building your own module manager in JAVASCRIPT

let’s explore javascript by building our own module manager in JAVASCRIPT

Posted by on October 23, 2016

Hey,

Fellow developers all around the word Hope you all doing great. Javascript is a powerful language by its own but still flooded with a lot of frameworks hiding what plain javascript can do when used correctly. So let’s explore javascript by building our own module manager in javascript ( it’s pretty easy. piece of cake ).

Quick Note : You can browse the whole code here at github.

You are familiar with them , you use them everyday and of course you love them.

You are familiar with them , you use them everyday and of course you love them. Yes, you guessed they are modules.

But ever wonder how they work from inside ? how they manage their module dependencies ? we are going to find the answer to these questions today by building a module manager which is capable of

  • Dependency injection ( use them inside another module)
  • Adding new modules
  • Requiring modules

Building your own module manager in javascript

It’s really is piece of cake

ok let’s start .. firstly we are going to create an index.html file and include our main module-manager.js file into it

<!DOCTYPE html>
<html>
<head>
    <title> Module Manager </title>
</head>
<body>

<script type="text/javascript" src="module-manager.js"></script>
</body>
</html>

now let’s create our module-manager.js file and write some code into it for a test run

write this line in your module-manager.js file

console.log('I am a module manager')

now open your index.html in the browser and navigate to console and see the results.

So now we are all set up. Let’s start working on our module manager.

Start by defining a variable to store our Module manager

var Manager = '';

Now I am going to define our manager .. so hang on tight

var Manager = (
    function Manager() {

        var modules = {
            dummy: function(name) {
                console.log("Hello My name is " + name)
            }
        };

        return modules;
    }
)();

this is our module manager .. their is lots of things going on right now .. so keep calm and let me … walk you through what we just written.

  • In our first line we are assigning an IIFE ( Immediately Invoked Function Expression ) … you can follow the link and give it a good read …. but in simple words .. IIFE is a function which gets executed at the same time you define it no need to call it somewhere else to execute it. In our case we are storing the variable modules returned by our IIFE function Manager into variable Manager.

  • the third line is pretty much obvious we are defining an object modules with a method named dummy which takes an argument name and print it into console upon execution.

  • in to last line we are returning modules variable.

now let’s test run this code but before that in your module-manager.js in the last line write this

Manager.dummy('Manoj');

now we are calling the dummy function which is stored in Manager to see if everything working fine.

Manager.define & Manager.require

Ok so let’s move on. Now what we are going to do is we will have two methods inside our module manager … with their help we will define and require our modules … to define our module we are going to use Manage.define and to require our module we are going to use Module.require .

So let’s define require first it is easy and pretty much straight forward.

var Manager = (
    function Manager() {

        var modules = {
            dummy: function(name) {
                console.log("Hello My name is " + name)
            }
        };

        function require(module_name) {
            return modules[module_name];
        }

        return {
            require: require
        }
    }
)();

what we are doing above is we are defining a function require which takes a module_name for the argument and returns the module from modules.

In the last line we are returning require function to save it into Manager variable

to test run the code write this code below Manager variable …

var dummy = Manager.require("dummy");

dummy("Manoj");

Now we are using require method of the Manager to get our dummy module and execute it.

And if everything works fine we are getting close .. to our module manager.

before writing our define function let’s see how our module definition will look like

Manager.define("module name", [ "module dependency" ], function (module_dependency){
    
    // module code

    return {
        methods: methods,
        property: property
    };
})

let’s write our define function now

function define(module_name, dependencies, definition) {
    for (var i = 0; i < dependencies.length; i++) {
        dependencies[i] = modules[dependencies[i]];
    }
    modules[module_name] = definition.apply(definition, dependencies);
}

  • firstly we are defining our function with three parameter module_name , dependencies , and function definition.

  • Then inside our define function we are iterating over our new module dependencies and replacing them with their real definition.

  • After that we are storing our return value provided by the new definition by using javascript apply function. You should follow the link and have a good read about apply function in simple terms apply takes the function definition and executes the function with its arguments

Now let’s define our first module but before that let’s make our modules variable an empty object .

var modules = {};

Now let’s define our module

Manager.define("output", [], function(){
    function write (name) {
        console.log(name);
    }

    return {
        write: write
    }
});

In the above code we are defining a module named output with no dependency and a method name write which output the argument name onto the console.

Let’s use it in our code.

// you can require module by Manager.require(“module_name”);
Var output = Manager.require(output);
output.write(Manoj);

Reload your index.html and see if it output the name your provided.

Let’s write another module to demonstrate dependency injection …

Manager.define("calculate", ["output"], function(output) {

    function add () {
        var total = 0;
        for(var i = 0; i < arguments.length; i++) {
            total += arguments[i];
        }
        output.write(total);
    }

    return {
        add: add
    }

})

var calculate = Manager.require("calculate")

calculate.add(3, 4, 5, 6);

In this module named calculate we are defining output module as a dependency. When we provide the dependencies of our module it automatically injects the requested module into ours so we can use it inside. Pretty cool ha ?

Test run this code in the browser and see if everything works fine … and if it is my friend welcome to the world of plain javascript :=).

Here is our full code.

var Manager = (
    function Manager() {

        var modules = {};

        function require(module_name) {
            return modules[module_name];
        }

        function define(module_name, dependencies, defination) {
            for (var i = 0; i < dependencies.length; i++) {
                dependencies[i] = modules[dependencies[i]];
            }
            modules[module_name] = defination.apply(defination, dependencies);
        }

        return {
            require: require,
            define: define
        }
    }
)();

Manager.define("output", [], function(){
    function write (data) {
        console.log(data);
    }

    return {
        write: write
    }
});

Manager.define("calculate", ["output"], function(output) {

    function add () {
        var total = 0;
        for(var i = 0; i < arguments.length; i++) {
            total += arguments[i];
        }
        output.write(total);
    }

    return {
        add: add
    }

})

var calculate = Manager.require("calculate")

calculate.add(3, 4, 5, 6);

And here it is your own module manager written entirely … in plain javascript.


Hey there. Follow along.