JavaScript Modules
14 April 2025 | Category: JavaScript
JavaScript Modules allow you to split your code into separate files, making it easier to manage, maintain, and reuse code. Modules were officially introduced in ES6 (ECMAScript 2015) and are now a core part of writing clean, scalable JavaScript applications.
đ What Are Modules?
A module is a JavaScript file that exports variables, functions, classes, or objects so that they can be imported and used in other JavaScript files.
đŻ Why Use Modules?
- Code Reusability: Use the same function or component in multiple files.
- Maintainability: Keep related logic in dedicated files.
- Namespace Isolation: Avoid polluting the global scope.
- Scalability: Essential for large applications (like React, Vue, etc.).
đ§Ș Example: Creating and Using Modules
đ math.js
(Exporting module)
// Named exports
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
// Default export
const multiply = (a, b) => a * b;
export default multiply;
đ main.js
(Importing module)
// Importing named exports
import { add, subtract } from './math.js';
// Importing default export
import multiply from './math.js';
console.log(add(5, 3)); // 8
console.log(subtract(5, 3)); // 2
console.log(multiply(5, 3)); // 15
Note: In Node.js or bundlers like Webpack, you’ll need to ensure the file is treated as a module using
"type": "module"
inpackage.json
, or use.mjs
extension.
đ€ Exporting
1. Named Export
You can export multiple values using export
in front of each item.
export const PI = 3.14;
export function greet(name) {
return `Hello, ${name}!`;
}
Or group them together:
const PI = 3.14;
const greet = name => `Hello, ${name}`;
export { PI, greet };
2. Default Export
Each module can only have one default export:
export default function sayHi() {
console.log("Hi!");
}
đ„ Importing
1. Named Import
import { greet, PI } from './module.js';
2. Default Import
import sayHi from './module.js';
3. Renaming Imports
import { greet as sayHello } from './module.js';
đ§ Dynamic Imports
Modules can also be loaded dynamically using import()
syntax (returns a promise).
async function loadModule() {
const module = await import('./math.js');
console.log(module.add(2, 3));
}
loadModule();
â Useful for code splitting and lazy loading in apps.
đ Modules in Browsers
In HTML:
<script type="module" src="main.js"></script>
â Modules are deferred by default
â import/export
works only inside type="module"
scripts
đ§± Modules in Node.js
In Node.js (v12+), to use ES modules:
- Set
"type": "module"
inpackage.json
- Use
.js
or.mjs
files
{
"type": "module"
}
OR
node --experimental-modules main.mjs
đ Key Benefits
Feature | Benefit |
---|---|
import/export | Organize code into small reusable units |
Scope isolation | Avoid global variable conflicts |
Static structure | Easier for bundlers and optimization |
Dynamic imports | Load code only when needed |
đ« Common Errors
- Cannot use import statement outside a module: Make sure you use
type="module"
in HTML or configure your bundler properly. - SyntaxError: Unexpected token ‘export’: File is not treated as a module (e.g., in CommonJS environments).
đ Conclusion
JavaScript Modules bring structure and clarity to modern JavaScript development. Whether you’re building a small script or a large web application, using modules helps keep your code clean, maintainable, and scalable.