There seems to be some confusion when it comes to JavaScript modules and how they exactly work, and why are there different forms in which we can use them. Today I’ll explain the different ways in which you can export and import modules.

Some background on JavaScript modules

JavaScript programs started as simple scripts or apps with rather small codebases, but as it has been evolving and so its uses have been increasing the size of the codebases have increased drastically. To support this increase the language needed to support a mechanism under which was possible to separate or split the code into smaller, reusable units. Node.JS had that ability for a while before it was incorporated in JavaScript with a feature called modules. And thus eventually they made it to the language itself and the browsers.

By definition, a module is just a file which can be imported from other modules (or files) through the help of directives like export and import:

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

We’ll come back to more of that later.


Introducing an example

To demonstrate the use of modules we will create a simple user module that will expose a User class. Let’s review the basic structure for the project:

index.html
scripts/
    index.js
    modules/
        user.js

Our app will be very simple and it will just show the name of a user on the screen, but the interesting part is that the name will come from an object instance of the User class. Let’s see it in action with a live demo:

Let’s look in detail what’s going on there by parts

#javascript #modules #programming

An Intro to JavaScript Modules
1.35 GEEK