JavaScript Modules — Import, Export, and Modular Code

Learn ES6 modules, CommonJS, dynamic imports, and how to organize your JavaScript codebase with modular architecture.

JavaScript Intermediate 📖 8 min

ES6 Module Syntax

// math.js — Named exports
export const PI = 3.14159;
export function add(a, b) { return a + b; }

// utils.js — Default export
export default function formatDate(date) {
  return new Intl.DateTimeFormat('en-US').format(date);
}

// app.js — Importing
import { add, subtract } from './math.js';
import formatDate from './utils.js';
import * as math from './math.js';

Dynamic Imports

// Lazy load a module
async function loadFeature() {
  const { FeatureComponent } = await import('./features/Feature.js');
  return FeatureComponent;
}

// Route-based code splitting
const routes = {
  '/dashboard': () => import('./pages/Dashboard.jsx'),
  '/settings': () => import('./pages/Settings.jsx'),
};

Re-exports (Barrel Files)

// index.js
export { add, subtract } from './math.js';
export { default as formatDate } from './utils.js';
export * from './constants.js';

// Usage
import { add, formatDate, API_URL } from './index.js';

Tree Shaking Tips

// BAD: imports entire lodash
import _ from 'lodash';

// GOOD: import only what you need
import debounce from 'lodash/debounce';

Ready to Level Up Your Coding Skills?

Join Coderz Club and learn to code with challenges, battles, and an AI mentor.

Join Coderz Club Free →