# Modules vs Namespaces

> The shift to standard ES Modules.

Subject: TypeScript | Lesson 46 of 54 | 3 min read
Interactive lesson: https://codewithanimation.in/typescript/modules-vs-namespaces
Previous: [Modern Decorators](https://codewithanimation.in/typescript/decorators.md) | Next: [tsconfig Compiler Flags](https://codewithanimation.in/typescript/tsconfig-compiler-flags.md)

## The Evolution of Scope

Before JavaScript had standard `import/export` syntax (ES Modules), TypeScript invented its own module system called `namespace`.

Today, standard ES Modules are natively supported by Node.js and all modern browsers, making TS namespaces largely obsolete.

## Why Switch?

Namespaces compile down to instantly-invoked function expressions (IIFEs) attached to the global object. This makes tree-shaking (removing unused code during build) nearly impossible for modern bundlers like Vite or Next.js.

ES Modules use a static structure that bundlers can analyze easily.

## Syntax

```typescript
// ❌ Legacy Namespaces
namespace Geometry {
  export function area(r: number) { return Math.PI * r * r; }
}
/// <reference path="geometry.ts" />
Geometry.area(5);

// ✅ Modern ES Modules
export function area(r: number) { return Math.PI * r * r; }
import { area } from "./geometry.js";
area(5);
```

## Common mistake: When to still use Namespaces?

You should almost *never* write application code using namespaces.

The only valid modern use case for namespaces is inside `.d.ts` declaration files when you need to type an older library that explicitly modifies the global window object (like `jQuery`).

## Tip: Global Augmentation

If you need to add custom properties to the global `window` object in an ES Module, you use a special namespace declaration: `declare global { interface Window { myVar: string; } }`.

## Try it: Try it

Compare the legacy `namespace` syntax alongside its compiled JavaScript output against the clean, modern ES Module standard.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/typescript/modules-vs-namespaces

## Check yourself

### Question 1

Why are Namespaces bad for modern web development?

- A. They are slower to execute than ES Modules.
- B. They compile to IIFEs which makes dead-code elimination (tree-shaking) difficult for bundlers.
- C. They are not supported in TypeScript 5.0+.

Correct answer: B

Namespaces bundle into giant objects. If you only use one function out of a 100-function namespace, the other 99 functions still get sent to the browser. ES Modules allow bundlers to drop the unused 99.

- Why not C: They are still supported for backwards compatibility.

## Remember this

- TypeScript `namespace` is a legacy feature from before ES Modules existed.
- Always use standard `import/export` syntax in modern apps.
- Namespaces break tree-shaking and bloat your bundle size.
- Only use namespaces in `.d.ts` files to type legacy global scripts.
