TypeScript Modules & Namespaces

6 Kernkonzepte
Die wichtigsten Konzepte für Module und Namespaces in TypeScript: ES Modules · Namespaces · import / export · default export · ambient declarations · d.ts TypeScript unterstützt sowohl ES-Module (modern) als auch Namespaces (klassisch) für die Organisation von Code. Diese Konzepte sind essenziell für die Entwicklung skalierbarer Anwendungen.

ES Modules – Export / Import (modern)

export · import · from
// module.ts export const PI = 3.14; export function add(a: number, b: number) { return a + b; } // main.ts import { PI, add } from "./module";

ES Modules sind der moderne Standard für die Code-Organisation in TypeScript. Sie verwenden export und import und werden von allen gängigen Build-Tools unterstützt.

Export-Varianten

Syntax Beschreibung
export const x = ... Benannter Export
export { x, y } Benannter Export (Liste)
export default x Standard-Export (ein pro Modul)
export * from "./module" Alle Exporte weiterleiten
export { x as y } Export mit Alias
Beispiele
// math.ts
export const PI = 3.14159;
export function square(x: number): number { return x * x; }
export interface Point { x: number; y: number; }
// app.ts
import { PI, square, Point } from "./math";
// Import mit Alias
import { square as sq } from "./math";
// Alles importieren
import * as MathUtils from "./math";
console.log(MathUtils.PI);
Tipp: ES Modules sind der empfohlene Weg für neue Projekte. Sie werden von Node.js (mit "type": "module") und allen Browsern (mit <script type="module">) unterstützt.

Namespaces – Code-Organisation (klassisch)

namespace · export · /// <reference
// shapes.ts namespace Shapes { export class Circle { /* ... */ } export class Square { /* ... */ } } // main.ts /// <reference path="shapes.ts" /> const circle = new Shapes.Circle();

Namespaces sind die klassische Methode zur Code-Organisation in TypeScript. Sie gruppieren Code logisch und vermeiden globale Namenskonflikte. Sie werden heute oft durch ES Modules ersetzt.

Beispiele
// geometry/figures.ts
namespace Geometry {
export namespace Figures {
export class Triangle { /* ... */ }
export class Rectangle { /* ... */ }
}
export function calculateArea(shape: any) { /* ... */ }
}
// Verwendung
/// <reference path="geometry/figures.ts" />
const tri = new Geometry.Figures.Triangle();
Geometry.calculateArea(tri);
Tipp: Namespaces sind nützlich für ältere Codebasen oder wenn Sie Code ohne Bundler verwenden. Für neue Projekte bevorzugen Sie ES Modules.

Import Syntax – Verschiedene Import-Wege

import · require · dynamic import
// Benannte Imports import { Component, OnInit } from "@angular/core"; // Standard-Import import React from "react"; // Dynamischer Import const module = await import("./module");

Import ist der Mechanismus, um Funktionen, Klassen oder Variablen aus anderen Modulen zu laden. TypeScript unterstützt verschiedene Import-Syntaxen für unterschiedliche Anwendungsfälle.

Beispiele
// Benannte Importe
import { find, map } from "lodash";
// Import mit Alias
import { Component as Comp } from "@angular/core";
// Namespace-Import
import * as fs from "fs";
// Standard- und benannte Importe kombinieren
import React, { useState, useEffect } from "react";
// Dynamischer Import (Code Splitting)
async function loadModule() {
const { default: Module } = await import("./heavy-module");
return new Module();
}
Tipp: Dynamische Imports (await import()) ermöglichen Code Splitting und lazy loading – besonders nützlich für große Anwendungen.

Export Syntax – Code bereitstellen

export · default · export *
// Benannte Exports export const API_URL = "https://api.example.com"; export function fetchData() { /* ... */ } // Standard-Export export default class Logger { /* ... */ } // Weiterleitung export * from "./module";

Export definiert, welche Teile eines Moduls von außen verwendet werden können. TypeScript unterstützt benannte Exports, Default-Exports und die Weiterleitung von Exports.

Beispiele
// utils.ts
export const VERSION = "1.0.0";
export function formatDate(date: Date): string { /* ... */ }
// Export mit Alias
const _log = (msg: string) => console.log(msg);
export { _log as log };
// Default Export (nur einmal pro Modul)
export default class Validator {
validate(input: string): boolean { /* ... */ }
}
// index.ts (Exporte bündeln)
export * from "./utils";
export { default as Validator } from "./validator";
Tipp: Verwenden Sie export default für die Hauptfunktion oder Hauptklasse eines Moduls. Verwenden Sie benannte Exports für Hilfsfunktionen und Konstanten.

Default Export – Hauptexport eines Moduls

export default · import ohne { }
// logger.ts export default class Logger { /* ... */ } // app.ts import Logger from "./logger"; const log = new Logger();

Default Export ermöglicht es, dass ein Modul genau einen Haupt-Export bereitstellt. Der Import erfolgt ohne geschweifte Klammern und kann beliebig benannt werden.

Beispiele
// Default Export einer Funktion
export default function greet(name: string): string {
return `Hallo ${name}`;
}
// Default Export einer Konstante
export default const config = {
apiUrl: "https://api.example.com",
timeout: 5000
};
// Import mit beliebigem Namen
import myGreeting from "./greeter";
import appConfig from "./config";
// Default und benannte Imports kombinieren
import Component, { Input, Output } from "@angular/core";
Tipp: Ein Modul kann nur einen Default-Export haben. Dies ist ideal für Bibliotheken, die eine Hauptfunktion oder Hauptklasse bereitstellen (z.B. React, Lodash).

Ambient Declarations – Typen für externe Bibliotheken

declare · d.ts · @types
// globals.d.ts declare const ENV: { API_URL: string }; declare function myLibrary(options: any): void; declare module "my-module" { export function doSomething(input: string): void; }

Ambient Declarations beschreiben die Typen von existierendem JavaScript-Code – ohne ihn zu kompilieren. Sie werden in .d.ts-Dateien definiert und ermöglichen die Typsicherheit für externe Bibliotheken.

Beispiele
// node.d.ts
declare module "fs" {
export function readFileSync(path: string, encoding: string): string;
export function writeFileSync(path: string, data: string): void;
}
// module.d.ts für eine JS-Bibliothek
declare module "my-js-lib" {
export interface Options {
delay: number;
retries: number;
}
export default function myLib(options: Options): void;
}
// Globale Deklaration
declare interface Window {
__INITIAL_STATE__: any;
ga: Function;
}
// Typ-Sicherheit für Umgebungsvariablen
declare namespace NodeJS {
interface ProcessEnv {
API_URL: string;
NODE_ENV: "development" | "production";
}
}
Tipp: Verwenden Sie @types-Pakete für gängige Bibliotheken (z.B. npm i --save-dev @types/node). Für eigene JS-Bibliotheken erstellen Sie .d.ts-Dateien manuell.

TypeScript Modules & Namespaces im Überblick

import Code importieren
from, require, async
export Code exportieren
default, benannt, *
namespace Code gruppieren (klassisch)
/// <reference
d.ts Typdeklarationen
ambient declarations
@types Typen für Bibliotheken
DefinitelyTyped
module Modul-Deklaration
declare module "..."

Quick Summary

ESM
ES Modules
ns
Namespaces
import
Code importieren
export
Code exportieren
default
Default Export
d.ts
Typdeklarationen
export const x = 1 · import { x } from "./module" · export default class MyClass