As our application grows larger, it's essential to divide the code into several files, or "modules". A module can contain a class or a library of functions for a specific purpose. JavaScript didn’t have a language-level module system for a long time, but as scripts grew more complex, the community developed various module-loading systems.
Some examples of module systems:
A module is simply a file. Scripts can load one another, call functions, and exchange functionality using export
and import
directives.
Here's an example:
mathModule.js (Module exporting functions):
// mathModule.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
app.js (Main script importing the module):
// app.js
import { add, subtract } from './mathModule.js';
console.log(add(5, 3)); // Output: 8
console.log(subtract(9, 4)); // Output: 5
Modules always operate in strict mode. For example, assigning to an undeclared variable in a module will throw an error, while regular scripts may not:
Example:
// mathModule.js
export function multiply(a, b) {
result = a * b; // Error: 'result' is not declared
return result;
}
Each module has a unique top-level scope, so variables and functions within a module are not visible to other scripts unless exported.
// user.js
let user = { name: "Harsh Kumar", role: "Blogger" }; // Not exported
Modules are only evaluated once. Importing the same module in multiple places will only execute its code the first time.
Example:
// logger.js
console.log("Logger module executed");
export function logMessage(message) {
console.log(`Message: ${message}`);
}
// main.js
import { logMessage } from './logger.js';
logMessage("Main script is running"); // Output: Logger module executed
// helper.js
import { logMessage } from './logger.js';
logMessage("Helper script is running"); // Output: Message: Helper script is running
import.meta
provides information about the current module, such as its URL.
// script.js
console.log(import.meta.url); // Outputs: https://example.com/scripts/script.js
JavaScript modules divide functionality into distinct files, improving code organization and reusability. Modules enable the sharing of variables, functions, and classes between files using export
and import
. Even if a module is imported more than once, it is evaluated only once. Every module has its own scope and strict mode. import.meta
contains information such as the URL of the module, which enhances performance, maintainability, and clean coding practices.