JavaScript Modules and Import/Export in Depth
(Organize code into reusable and maintainable blocks with ES Modules)
What Are JavaScript Modules?
Modules allow you to split your code into multiple files, keeping your codebase clean and organized. Each file can export variables, functions, or classes, and other files can import them.
This modular approach helps in:
- Code Reusability
- Maintainability
- Namespace Isolation (no global scope pollution)
Enabling Modules
To use modules in the browser, add type="module"
in your <script>
tag:
<script type="module" src="main.js"></script>
Exporting from a Module
You can export functions, variables, or classes from a module file.
Named Exports
// file: mathUtils.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
You can also export after declaration:
const multiply = (a, b) => a * b;
export { multiply };
Importing Named Exports
// file: main.js
import { add, subtract } from './mathUtils.js';
console.log(add(5, 3)); // 8
console.log(subtract(5, 3)); // 2
You can also alias the import:
import { add as sum } from './mathUtils.js';
Default Exports
A module can have one default export.
// file: greet.js
export default function greet(name) {
console.log(`Hello, ${name}`);
}
Importing a default export:
import greet from './greet.js';
greet('Alice'); // Hello, Alice
Mixing Named and Default Exports
// file: utils.js
export const log = msg => console.log(msg);
export default function sayHi() {
console.log("Hi!");
}
import sayHi, { log } from './utils.js';
Export All from Another File
You can re-export everything from another module:
// file: allUtils.js
export * from './mathUtils.js';
Importing All as an Object
// file: main.js
import * as math from './mathUtils.js';
console.log(math.add(2, 3)); // 5
Modules Are Strict Mode by Default
You don't need "use strict"
in module files — they run in strict mode automatically.
Modules Run in Their Own Scope
Variables in modules are local
to that module. They don’t leak into the global scope.
Browser Compatibility and Notes
- Modern browsers fully support modules.
- When using modules locally, you must serve files using a local server (e.g.,
Live Server
in VS Code orhttp-server
) — otherwise, you may get CORS or loading errors. - In Node.js, use
.mjs
extension or set"type": "module"
inpackage.json
to use ES modules.
Summary
- ES Modules let you organize code into small, reusable files.
- Use
export
andimport
to share code across files. - Modules are scoped, strict, and avoid polluting the global namespace.
- Mastering modules is essential for scalable applications and working with modern frameworks.
🧪 Practice Exercise:
Task:
- Create a
math.js
file and exportadd
,subtract
,multiply
,divide
. - Create a
main.js
file that imports and uses all those functions. - Use default export for a
greet()
function in a separate module. - Use
import *
as syntax to bring all exports into one object. - Try mixing named and default exports in a utilities file.