Back to Tutorials
📦 Intermediate

JavaScript Modules

6 min read | Modules

JavaScript Modules

Modules help organize code into reusable pieces.

ES Modules (ESM)

Named Exports

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

// main.js import { PI, add, multiply } from './math.js'; import { add as sum } from './math.js'; // Rename import * as math from './math.js'; // Import all

Default Export

// user.js
export default class User {
  constructor(name) {
    this.name = name;
  }
}

// main.js import User from './user.js'; import MyUser from './user.js'; // Any name works

Mixed Exports

// utils.js
export default function main() {}
export const helper = () => {};
export const VERSION = '1.0.0';

// main.js import main, { helper, VERSION } from './utils.js';

Dynamic Imports

// Lazy loading
const module = await import('./heavy-module.js');
module.doSomething();

// Conditional loading if (needsFeature) { const { feature } = await import('./feature.js'); feature(); }

Re-exporting

// index.js (barrel file)
export { default as User } from './user.js';
export { default as Post } from './post.js';
export * from './utils.js';

// main.js import { User, Post } from './models/index.js';

Module Patterns

// Singleton
let instance;
export default function getInstance() {
  if (!instance) {
    instance = createInstance();
  }
  return instance;
}

// Factory export function createLogger(prefix) { return { log: (msg) => console.log([${prefix}] ${msg}) }; }