Skip to main content

JavaScript Modules: Import and Export Explained

Updated 2 min readMarkdown
JavaScript Modules: Import and Export Explained

JavaScript Modules: Import and Export Explained Simply Imagine writing an entire novel in a single text file. Characters, plot, dialogue, world-building — all crammed together with no chapters, no sections. That's what a JavaScript app without modules looks like: one giant file that becomes a nightmare to read and maintain. Modules let you split your code into logical pieces and share what's needed between files.

What Is a Module? A module is simply a JavaScript file that exports some values (functions, variables, classes) and imports what it needs from other files. There are two module systems you'll encounter:

CommonJS — used in Node.js (require / module.exports) ES Modules — modern standard (import / export)

CommonJS (Node.js Style) Exporting: js// math.js function add(a, b) { return a + b; }

function subtract(a, b) { return a - b; }

module.exports = { add, subtract }; Importing: js// app.js const { add, subtract } = require('./math');

console.log(add(5, 3)); // 8 console.log(subtract(10, 4)); // 6

ES Modules (Modern JavaScript) Named Exports: js// utils.js export function greet(name) { return Hello, ${name}!; }

export const PI = 3.14159; Named Imports: js// main.js import { greet, PI } from './utils.js';

console.log(greet('Priya')); // Hello, Priya! console.log(PI); // 3.14159 Default Exports: js// logger.js export default function log(message) { console.log([LOG]: ${message}); } js// app.js import log from './logger.js';

log('Server started'); // [LOG]: Server started You can name a default import anything you like — the name doesn't matter.

Named vs Default: When to Use Which FeatureNamed ExportDefault ExportMultiple per file✅ Yes ❌ Only one Import syntax{ name }Any nameBest forUtilities, constantsMain class/function

Importing Everything with * as jsimport * as MathUtils from './math.js';

console.log(MathUtils.add(2, 3)); // 5

Using ES Modules in Node.js Either rename your file to .mjs, or add "type": "module" to your package.json: json{ "type": "module" }

Beginner Mistakes

Forgetting ./ before the file path (require('math') looks in node_modules, not your file). Mixing CommonJS and ES Module syntax in the same file. Exporting a value but forgetting to import it elsewhere.

Quick Summary Modules are how JavaScript stays organized at scale. CommonJS (require) works great in Node.js. ES Modules (import/export) are the modern standard and are supported in browsers natively. Pick one style per project and stay consistent.

3 views

No comments yet. Be the first to comment.