Module Loader in JavaScript

  1. Module in JavaScript
  2. Module Loader in JavaScript
Module Loader in JavaScript

This article will learn what a module loader is in JavaScript and how to use a module loader to load JavaScript modules in the main JavaScript file by an instance with an example.

Module in JavaScript

The multiple statements of code used to summarize implementation details and execute specific tasks are known as the module. It can also be reused, and we can avoid writing similar code repeatedly.

We can load and use our module in another code source. We can use the module to transpose dependencies easily to manage them.

Module basic pattern:

We can create a module with the pattern, as shown below.

// Expose module as a global variable

var MyModule = function() {
  // Inner logic of the module

  function helloWorld() {
    console.log('Hello world');  // will print "Hello world" in log
  }

  // Expose API

  return {
    helloWorld: helloWorld
  }
}

Now, we can create an instance of our module, as shown below.

var module_instance = new MyModule();

Now, we can access its public API.

module_instance.helloWorld();

Module Loader in JavaScript

To interpret and load an already written module in a specific module format, we use module loaders that will execute at the run time of the source code. Module loader loads in the browsers.

We need to define the main file for the module loader to load. The module loader performs interpreting and downloading the main file.

There are a few module loader examples in JavaScript.

  • RequireJs
  • SystemJs

RequireJs

RequireJs is a library that supports the AMD (Asynchronous Module Definition) standards. As shown below, we have to download and load RequireJs in our HTML document.

<script src="scripts/require.js"></script>

Before or after the require.js script is loaded, RequireJs can be configured. We need to describe a variety of required names and store the configuration.

SystemJs

In JavaScript, SystemJs is a universal module loader. In angular for module loading, it is used immensely.

If we need a jQuery library in our main.js file, we can start our main.js file with the import keyword, and it will automatically load jQuery library modules. Using SystemJs, we can load separate JavaScript modules in our main JavaScript file, as shown below.

System.Import('main.js');