Appearance
Kapitel 14: Modularisierung (import / export)
14.1 Was ist Modularisierung?
📦 Warum Modularisierung?
Modularisierung erlaubt es, Code in mehrere Dateien aufzuteilen (wie bei Büchern in einem Regal).
| Vorteil | Beschreibung |
|---|---|
| Wiederverwendbarkeit | Code kann in anderen Dateien verwendet werden |
| Bessere Organisation | Code ist logisch getrennt |
| Namenskonflikte vermeiden | Jedes Modul hat seinen eigenen Scope |
| Einfacheres Debuggen | Fehler sind leichter zu lokalisieren |
🔍 ES6 Module vs CommonJS (Node.js)
| Aspekt | CommonJS (Node.js) | ES6 Module |
|---|---|---|
| Export | module.exports = ... | export ... |
| Import | const ... = require(...) | import ... from '...' |
| Statisch | ❌ Dynamisch | ✅ Statisch (bessere Optimierung) |
| Tree Shaking | ❌ Nicht möglich | ✅ Möglich |
14.2 export - Exportieren
📤 export Grundlagen
javascript
// math.js
// 1. Named Export (benannte Exporte)
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export const subtract = (a, b) => a - b;
// 2. Default Export (Standard-Export) - siehe 14.4📤 Mehrere Exporte in einer Zeile
javascript
// utils.js
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
const multiply = (a, b) => a * b;
const divide = (a, b) => a / b;
// Alle auf einmal exportieren
export { add, subtract, multiply, divide };🎯 Was kann exportiert werden?
javascript
// 1. Variablen
export const API_URL = "https://api.example.com";
// 2. Funktionen
export function greet(name) {
return `Hallo ${name}!`;
}
// 3. Klassen
export class Person {
constructor(name) {
this.name = name;
}
}
// 4. Objekte
export const CONFIG = {
retry: 3,
timeout: 5000
};14.3 import - Importieren
📥 import Grundlagen
javascript
// main.js
import { PI, add, subtract } from './math.js';
console.log(PI); // 3.14159
console.log(add(2, 3)); // 5
console.log(subtract(5, 2)); // 3Wichtig: .js Erweiterung nicht vergessen (bei lokalen Dateien)!
📥 Alles auf einmal importieren
javascript
// main.js
import * as math from './math.js';
console.log(math.PI); // 3.14159
console.log(math.add(2, 3)); // 5
console.log(math.subtract(5, 2)); // 3* as math bedeutet: Alles aus math.js unter dem Namen math importieren.
🎯 Import-Pfade
javascript
// 1. Relativer Pfad (lokale Datei)
import { add } from './math.js';
import { Person } from '../models/person.js';
// 2. Absoluter Pfad (mit Bundler wie Vite/Webpack)
import { API_URL } from '/src/config.js';
// 3. Node_Modules (Bibliotheken)
import _ from 'lodash';
import React from 'react';14.4 Default Export vs Named Export
📤 Default Export (Standard-Export)
Jedes Modul kann nur einen Default Export haben.
javascript
// person.js
class Person {
constructor(name) {
this.name = name;
}
}
// Default Export
export default Person;Importieren (Name frei wählbar!):
javascript
// main.js
import Person from './person.js'; // Name frei wählbar!
import P from './person.js'; // Auch möglich
const p = new Person("Max");📤 Named Export (benannte Exporte)
Jedes Modul kann mehrere Named Exports haben.
javascript
// math.js
// Named Exports
export const PI = 3.14159;
export function add(a, b) { return a + b; }Importieren (Name muss exakt übereinstimmen!):
javascript
// main.js
import { PI, add } from './math.js'; // Namen müssen exakt sein!
console.log(PI); // 3.14159
console.log(add(2, 3)); // 5📊 Vergleich: Default vs Named Export
| Aspekt | Default Export | Named Export |
|---|---|---|
| Anzahl | Maximal 1 pro Modul | Mehrere möglich |
| Import-Syntax | import Name from '...' | import { Name } from '...' |
| Name beim Import | Frei wählbar | Muss exakt übereinstimmen |
| Verwendung | Haupt-Export eines Moduls | Hilfsfunktionen / Konstanten |
🎯 Beide kombinieren
javascript
// utils.js
// Named Exports
export const PI = 3.14159;
export function add(a, b) { return a + b; }
// Default Export
export default class Calculator {
add(a, b) { return a + b; }
}Importieren:
javascript
// main.js
import Calculator, { PI, add } from './utils.js';
const calc = new Calculator();
console.log(calc.add(2, 3)); // 5
console.log(PI); // 3.14159
console.log(add(2, 3)); // 514.5 Renaming (Umbenennen beim Import/Export)
🏷️ Umbenennen beim Import (as)
javascript
// math.js
export const PI = 3.14159;
export function add(a, b) { return a + b; }Importieren mit neuem Namen:
javascript
// main.js
import { PI as Kreiszahl, add as plus } from './math.js';
console.log(Kreiszahl); // 3.14159
console.log(plus(2, 3)); // 5Grund: Namenskonflikte vermeiden.
🏷️ Umbenennen beim Export
javascript
// utils.js
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
// Beim Export umbenennen
export {
add as summe,
subtract as differenz
};Importieren:
javascript
// main.js
import { summe, differenz } from './utils.js';
console.log(summe(2, 3)); // 5
console.log(differenz(5, 2)); // 3🎯 Praxisbeispiel: Namenskonflikte vermeiden
javascript
// lib1.js
export function format(data) { /* ... */ }
// lib2.js
export function format(data) { /* ... */ }
// main.js
import { format as format1 } from './lib1.js';
import { format as format2 } from './lib2.js';
format1(data); // Verwendet format aus lib1
format2(data); // Verwendet format aus lib214.6 Praxis: Code in mehrere Dateien aufteilen
📂 Beispiel 1: Einfache Aufteilung
Projektstruktur:
src/
├── main.js
├── math.js
└── utils.jsmath.js:
javascript
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}utils.js:
javascript
export function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}main.js:
javascript
import { PI, add } from './math.js';
import { capitalize } from './utils.js';
console.log(PI); // 3.14159
console.log(add(2, 3)); // 5
console.log(capitalize("hallo")); // "Hallo"📂 Beispiel 2: Klassen aufteilen
Projektstruktur:
src/
├── main.js
├── models/
│ ├── Person.js
│ └── Student.js
└── utils/
└── helpers.jsmodels/Person.js:
javascript
export class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hallo, ich bin ${this.name}`;
}
}models/Student.js:
javascript
import { Person } from './Person.js';
export class Student extends Person {
constructor(name, matrikelnummer) {
super(name);
this.matrikelnummer = matrikelnummer;
}
}main.js:
javascript
import { Person } from './models/Person.js';
import { Student } from './models/Student.js';
const p = new Person("Max");
console.log(p.greet()); // "Hallo, ich bin Max"
const s = new Student("Erika", "12345");
console.log(s.greet()); // "Hallo, ich bin Erika"📂 Beispiel 3: Barrel File (Index-Datei)
Projektstruktur:
src/
├── main.js
└── utils/
├── math.js
├── string.js
└── index.js ← Barrel Fileutils/math.js:
javascript
export function add(a, b) { return a + b; }utils/string.js:
javascript
export function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); }utils/index.js (Barrel File):
javascript
export { add } from './math.js';
export { capitalize } from './string.js';main.js:
javascript
// ✅ Einfacher Import (von Barrel File)
import { add, capitalize } from './utils/index.js';
console.log(add(2, 3)); // 5
console.log(capitalize("hallo")); // "Hallo"🎉 Zusammenfassung
In diesem Kapitel hast du gelernt:
- ✅ Was Modularisierung ist (Code aufteilen)
- ✅
export(Named Export, Default Export) - ✅
import(Benannte Importe,*Importe) - ✅ Default Export vs Named Export
- ✅ Renaming (
asSchlüsselwort) - ✅ Praxisanwendung (Code aufteilen)
📝 Übung
Named Export:
javascript// Erstelle eine Datei 'math.js' mit den Funktionen 'add' und 'subtract' // Exportiere beide FunktionenDefault Export:
javascript// Erstelle eine Datei 'person.js' mit einer Klasse 'Person' // Exportiere die Klasse als Default ExportImport:
javascript// Importiere 'Person' und die Funktionen 'add', 'subtract' in 'main.js'
➡️ Nächstes Kapitel
In Kapitel 15 lernen wir neue String-Methoden in ES6+ (includes(), startsWith(), endsWith(), repeat(), padStart(), padEnd())!
