JavaScript Modules: Import and Export Explained
Modules can be classified as blocks consisting of code in our code-base, we can divide our code into smaller, keeping it clean and according to read-ablility.
We can organize them into different files based on the responsibility of the module, this not only avoids cluttering but gives us well labelled structure and code becomes easy to navigate
clean / readable
labelled, easy to navigate
Why modules?
In JavaScript, as applications grow, writing everything in a single file quickly becomes messy and hard to maintain. Modules allow us to split our code into separate files, each handling a specific task. (e.g.- separating APIs from UI)
Importing / Exporting Functions or Values
In JavaScript, we can export functions, variables, or classes from a file so they can be used elsewhere.
// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
Importing Modules
Once exported, these functions can be imported into another file.
// app.js
import { add, subtract } from './math.js';
console.log(add(2, 3)); // 5
console.log(subtract(5, 2)); // 3
Types of exports
JavaScript supports two types of exports:
Named Exports
export multiple items from a file.
// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
Default Export
A file can have one default export.
// logger.js
export default function log(message) { console.log(message); }
import
import log from './logger.js';
log("This is a log message");
Benefits
Clean code: Less clutter and easier to read and debug
Reusability: Write once and reuse across multiple parts of the application
Scalability: Easy to expand and maintain as the project grows