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
require
for imports andmodule.exports
for 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
define
for defining a module andrequire
for 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
import
andexport
keywords. - Can be used in the browser with the
type="module"
attribute. - Can be used in Node.js with the
.mjs
extension 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
import
statements get hoisted to the top of the file.- If using a top-level
await
, the module loading is deferred until the promise resolves. import
statements are synchronous, whereasimport()
functions are asynchronous.
Example Function
function getRohit() {
if (true) {
// Add functionality here
}
}
getRohit();