What is a JavaScript module and how to use it?
The thing with frontend frameworks and libraries is that you’ve got a scaffold to work against. There are set rules that you have to follow to make things work.
However, the front end by itself isn’t that useful. It might look good, but functionality-wise, it’s an isolated island. While there are APIs to connect to, sometimes, you just need to create your own backend.
In the world of node.js and backend API creation, it’s a pretty free world out there. Alternatively, you might be dreaming of a feature but don’t quite know how to implement it in a neatly packaged way. Understanding the basics of JavaScript is your path towards survival — with modules being a technic to help maintain your long term sanity.
But what is a module? How do you use and create one? These are some of the questions I’ll be answering here today.
What is a JavaScript module?
A module is more than just a buzzword. In JavaScript, it’s a piece of self-contained exportable code. To be modular means to be interchangeable. The entire code for that particular section of your application can be uplifted, moved and reused as needed.
If you’re coming from a frontend perspective, you would have already encountered modules before. It usually looks something like this:
import {anotherController} from './controllerThing.js';
export function someClassControllerThing(){}
So we know what a module sort of looks like — but how does it benefit the way you code?
When it comes to a JavaScript project that doesn’t have a framework to guide its structural integrity, you’re pretty much free to construct your app however you want.
You could, in theory, have it has one big file with global functions that have no boundaries attached to them. We’ve all been there at some point.
Originally, JavaScript code was just that — one big and long file that you had to manually trace through to figure out what was going on. Over time, as scripts became more complex in size and logic, the community decided that enough was enough and started to create ways to arrange code.
Modularity gives way to future maintainability. How? By keeping everything neatly packaged and contained, with clear domains of separation between codes.
The ability to create modules as we know it did not actually appear in JavaScript until around 2015. While the concept has been around in other languages, it wasn’t properly native until five years ago.
A collection of modules is called a library. A collection of coordinated libraries with an enforced rule for usage and implementation is called a framework. There is a little bit more to frameworks than just this, but it is beyond the intended scope for this piece.
How do you use a JavaScript module?
Using a JavaScript module is fairly simple. The thing with modules is that the creation and usage process is straightforward.