How do JavaScript modules and module loaders work ?
JavaScript modules are a way to organize and encapsulate code into reusable units. They allow developers to split their code into separate files, each containing a module with its own scope, and export specific values or functions to be used by other modules.
Module loaders, on the other hand, are tools or mechanisms that enable the loading and execution of modules in a JavaScript application. They provide features like dependency management, lazy loading, and code bundling.
The most common module system in JavaScript is the ES6 (ECMAScript 2015) module system, which is supported in modern browsers and in Node.js. ES6 modules use the import
and export
keywords to define dependencies and expose functionality between modules.
Here's a basic example of how modules work in JavaScript:
// math.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
// app.js
import { add, subtract } from './math.js';
console.log(add(5, 3)); // Output: 8
console.log(subtract(5, 3)); // Output: 2
In this example, the math.js
file exports the add
and subtract
functions using the export
keyword. The app.js
file then imports those functions using the import
statement and uses them in its own code.
Comments
Post a Comment