JavaScript Module Systems
Overview
Understanding JavaScript's module systems is essential for organizing and managing code effectively. Below are the major module systems used in JavaScript:
CommonJS (CJS)
- Modules are loaded synchronously, typically used on the server side.
- Uses
requirefor imports andmodule.exportsfor exports. - Requires bundling and transpiling to use in the browser.
- Very common in Node.js environments.
Syntax:
const module = require("module");
module.exports = value;
AMD (Asynchronous Module Definition)
- Modules and their dependencies are loaded asynchronously.
- Modules can be loaded at runtime when they are required.
- Uses
definefor defining a module andrequirefor importing. - Mostly used in the browser.
Syntax:
define(["dependency"], function (dependency) {
return module;
});
UMD (Universal Module Definition)
- Works with both client-side and server-side environments.
- Ideal for libraries intended to work in both environments.
ESM (ECMAScript Modules)
- Standardized module system introduced in ES6.
- Uses
importandexportkeywords. - Can be used in the browser with the
type="module"attribute. - Can be used in Node.js with the
.mjsextension or by setting"type": "module"inpackage.json. - Allows for tree shaking, static analysis, and more efficient bundling.
Syntax:
// Exporting
export const value = 42;
export default function () {}
// Importing
import value from "./module.js";
import { namedExport } from "./module.js";
Things to Remember
importstatements get hoisted to the top of the file.- If using a top-level
await, the module loading is deferred until the promise resolves. importstatements are synchronous, whereasimport()functions are asynchronous.
Example Function
function getRohit() {
if (true) {
// Add functionality here
}
}
getRohit();