Modules in JavaScript… #30daysof JavaScript ==> Day 27

Olajide Blessing Niniola
2 min readApr 2, 2022

--

Applications on the web have evolved from just being static and as these applications become more functional and complex, code organization becomes paramount. More codes are added to the application and managing it might become a nightmare. So what is a module?

A module is simply a file that holds other files using special directives such as import and export. Now, what are the essence of these directives? Well, they ensure that the files are accessible outside a folder (current module)that must have been created in the application allowing a block of code to be used outside of its own file.

export directive
import directive

Important notes about modules

  • Modules work only via HTTP(s), not locally: If you try to open a web page locally, via file:// protocol, you’ll find that import/export directives don’t work. A quick solution to this is to use the live server extension on your local IDE.
  • Modules always work in strict mode. E.g. assigning to an undeclared variable will give an error.
  • Each module has its own top-level scope. In other words, top-level variables and functions from a module are not seen in other scripts unless the variables used in declaring them are called.
  • Old browsers do not understand type="module". Scripts of an unknown type are just ignored. For them, it’s possible to provide a fallback using the nomodule attribute.
  • Module code is executed only once. Exports are created once and shared between importers.

For the most part, it is important to understand the concept of modules as it is seen across all JavaScript frameworks examples of these popular frameworks include Angular, React, Vue etc. But in the main time, check how modules can be used solely in javascript here.

What is this about?

30daysofjavascript is a series of writing on how I learned to code in JavaScript. These episodes are as simplified as possible and for beginners like me, I hope you find JavaScript less confusing throughout this episode. Thank you as always and see you in the next episode. Check out every episode I have written here.

--

--

No responses yet