JavaScript Modules – How modules help to reduce complexity of scripts

Free Web development courses with real-time projects Start Now!!

While developing in JavaScript, you will often hear jargon, including modules, module-patterns, etc. This tutorial will explain all that and more because if you don’t, you’ll quickly become overwhelmed with the project. It is a vital component for web developers, even though the module system can be quite intimidating. Stick with this JavaScript modules tutorial and gain all the knowledge you will need to get you started. We will begin with the what, why and how of JavaScript modules and proceed from there.

I can’t emphasize the significance of practicing what you learn enough. Implement what you learn in the article to get familiar with the concepts. Also, work on the codes parallelly with me so you get the hang of what’s happening in the code.

JavaScript Modules Tutorial

What are JavaScript Modules?

JavaScript modules are an implementation of closures, thus, I strongly suggest that you go through DataFlair’s JavaScript tutorial on Closures before you continue further with this topic.

Moving on, JavaScript modules (also called “ES modules” or “ECMAScript modules”) contain a class or a library of functions. Simply, modules are like a book chapter: a cluster of words (or code). Since initially, our scripts were small and simple, there was no need for modules in JavaScript. But, as our application increased in size and complexity, splitting it into multiple files (modules) made sense. Introduced in 2015, these have gradually evolved since then, and now all major browsers and NodeJS support them. Don’t forget, good modules are highly self-contained and have distinct functionality. This allows us to shuffle, add, or remove them as per our requirements, without disrupting the whole system.

Modules are nothing but files, which can load each other using the special directives import and export.

  • export: It labels variables and functions that should be accessible from outside the current module.
  • import: It allows us to import functionality from other modules.

We will learn more about these keywords further in this tutorial. For now, let’s focus on the advantages of using modules in your program.

Why use Modules?

There are numerous benefits of modules for a sprawling, interdependent codebase. Some of the most important ones are as follows:

Maintainability – Since modules are self-contained, they reduce the dependencies on parts of the codebase as much as possible to improve them independently. Also, updating a single module is much more convenient than updating the complete code. Updating one module doesn’t affect the other modules.

Namespacing – Since variables outside the scope of a top-level function are global, it’s common to have “namespace pollution” in our code. This means that totally unrelated code shares those global variables, creating confusion, resulting in unexpected outputs. Modules help us avoid these situations by creating private space for the variables.

You can’t afford to miss the JavaScript Variables Tutorial

Reusability – JavaScript modules let us copy the previous code into our program and reuse it over and over again. Writing the complete code for the same task is time-consuming; modules provide us with a better approach to optimize our code.

Now, we know how useful modules can be for our application.

How to Use JavaScript Modules?

The first thing you need to remember while working with modules is that they cannot work without a server connection. According to the CORS policy, export statements are only valid with a server; otherwise, the browser blocks the file. Thus, I recommend you to install XAMPP on your computer to work with the localhost. Next, open the browser and localhost/phpMyAdmin type in the address bar.

Exporting Module Features

The first step to use a module is to create one, which is possible with the help of the export keyword. We export all the variables and functions in the module so they are available for use to other files. Every module performs a specific task, and work only with the help of a server. The following program creates a JavaScript file and exports the data inside.

Code:

//export this file
export function hello(user) {
  return `Hello, ${user}!`;
}

In the code above, the return statement returns a string “Hello userName”, where userName is whatever name is sent as an argument at the time of function call.

Importing Features into your Script

The next step is to use the module in our program by the import statement. We import the module in the document and use its variables and functions, without having to redefine them. The statement binds the current document with the module, providing it with additional functionality. The following code imports the above module evaluates it and uses it to produce an output in the browser.

Code:

<html>
    <body>

        <script type="module">
            //import the JavaScript module from the file
            import {hello} from './hello.js';

            //use the hello() function, defined in the module
            document.body.innerHTML = hello('DataFlair');
        </script>

    </body>
</html>

The type attribute specifies that the script added is a module and treats it accordingly.

Core JavaScript Module Features

Regular scripts are different from the modules, differentiated by its core features. These features are valid for the browser as well as server-side JavaScript. The following are the core module features that distinguish modules:

Always use “strict”

By default, modules use the strict mode. For example, if you try to assign a value to an undeclared variable, you will get an error.

Code:

<script type="module">
    var1 = 5; // error
</script>

Module-level Scope

All modules have their own top-level scope. This means that other scripts cannot access the modules’ global (top-level) variables and functions. The module has to export everything it wants to grant access to the scripts. If you try to do so, the import fails and doesn’t add any functionality.

To create a window-level global variable, we can explicitly assign the variable to the window and access window.userName. But only use these variables with a reason because this is an exception to the case mentioned before.

Time to revise the concept of JavaScript Functions

Module code is only evaluated the first time when imported

If multiple places import the same module in a script, then it is only imported for the first time. After that, all the importers receive exports. But there are some consequences you need to be aware of.

Primarily, since the module only loads once, any statement that executes on the import triggers only once: the first time.

Practically, we use the top-level module code for the initialization and creation of internal data structures. If you want to make anything reusable, you can simply export it.

Let’s see how this affects our code with the help of a JavaScript program.

Code:

import.meta

The import.meta object stores all the information regarding the current module. The contents of the object depend on the environment.

Summary

With this, we have covered all the core aspects of JavaScript modules including reasons and method of using it. We also learned about the process to import features into your script and major features of the JavaScript module.

Next tutorial lined up for you – JavaScript Debugging and Testing

There is no need to remind you but still, if you have any doubts, share them in the comments section. We will be glad to assist you.

Happy Learning!

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *