Modulok
TypeScript modulok
A modulok segítségével a kódunkat külön fájlokba szervezhetjük. Minden fájl, amely import vagy export utasítást tartalmaz, egy modul. A modulokban deklarált változók, függvények, osztályok csak akkor érhetők el más fájlokból, ha explicit módon exportáljuk őket.
Fontos
Minden TypeScript fájl, ami tartalmaz top-level import vagy export utasítást, automatikusan modul lesz. A modulok saját scope-ban futnak, nem a globális scope-ban.
Exportálás
Named Export
A export kulcsszóval tehetünk láthatóvá interfészeket, osztályokat, függvényeket más modulok számára.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 | // Export interface directly
export interface Product {
id: number;
name: string;
price: number;
category: string;
}
// Export class directly
export class ProductHelper {
static formatPrice(price: number): string {
return `$${price.toFixed(2)}`;
}
static calculateDiscount(price: number, percentage: number): number {
return price * (1 - percentage / 100);
}
}
|
Vagy exportálhatunk a fájl végén is:
1
2
3
4
5
6
7
8
9
10
11
12
13 | interface Validator {
isValid(value: string): boolean;
}
class EmailValidator implements Validator {
isValid(email: string): boolean {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
}
// Export at the end
export { Validator, EmailValidator };
|
Export átnevezéssel
Átnevezhetjük az exportált elemeket:
| interface Validator {
isValid(value: string): boolean;
}
// Export with alias
export { Validator as IValidator };
|
Default Export
Minden modul rendelkezhet egy default exporttal. Ez azt jelenti számunkra, hogy az importáláskor nem kell kapcsos zárójelet használnunk.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 | interface CartItem {
product: Product;
quantity: number;
}
// Default export - no curly braces needed when importing
export default class ShoppingCart {
private items: CartItem[] = [];
addItem(product: Product, quantity: number): void {
this.items.push({ product, quantity });
}
getTotal(): number {
return this.items.reduce((total, item) => {
return total + (item.product.price * item.quantity);
}, 0);
}
}
|
Importálás
Named Import
A named exportokat kapcsos zárójelek között importáljuk:
| // Import specific exports
import { Product, ProductHelper } from './Product';
const laptop: Product = {
id: 1,
name: "Laptop",
price: 999.99,
category: "Electronics"
};
console.log(ProductHelper.formatPrice(laptop.price)); // "$999.99"
|
Import átnevezéssel
Az importált elemeket átnevezhetjük:
| import { Validator as IValidator } from './Validator';
import { EmailValidator as EmailChecker } from './Validator';
const validator: IValidator = new EmailChecker();
|
Default Import
A default exportot kapcsos zárójelek nélkül importáljuk:
1
2
3
4
5
6
7
8
9
10
11
12
13
14 | // No curly braces for default import
import ShoppingCart from './ShoppingCart';
import { Product } from './Product';
const cart = new ShoppingCart();
const laptop: Product = {
id: 1,
name: "Laptop",
price: 999.99,
category: "Electronics"
};
cart.addItem(laptop, 1);
console.log(cart.getTotal()); // 999.99
|
Namespace Import
Az összes exportot egy névtérbe importálhatjuk:
| // Import everything as namespace
import * as ProductUtils from './Product';
const laptop: ProductUtils.Product = {
id: 1,
name: "Laptop",
price: 999.99,
category: "Electronics"
};
console.log(ProductUtils.ProductHelper.formatPrice(laptop.price));
|
Újra-exportálás - Barrel export
Gyakran szeretnénk több modul exportjait egy helyen összegyűjteni. Ezt re-export-tal tehetjük meg.
| export interface Product {
id: number;
name: string;
price: number;
}
|
| export interface CartItem {
productId: number;
quantity: number;
}
|
| // Re-export everything from other modules
export * from './Product';
export * from './Cart';
// Or selectively
export { Product } from './Product';
export { CartItem } from './Cart';
|
Most már egyszerűen importálhatunk:
| // Instead of multiple imports from different files
import { Product, CartItem } from './models';
|
Típusok importálása
TypeScript 3.8-tól kezdve importálhatunk csak típusokat is az import type használatával:
| // Import only type (not runtime code)
import type { Product } from './models/Product';
// This ensures Product is only used as a type, not as a value
const product: Product = {
id: 1,
name: "Laptop",
price: 999.99,
category: "Electronics"
};
|
Összefoglalás
| Művelet |
Szintaxis |
Példa |
| Named export |
export { name } |
export { Product } |
| Default export |
export default class |
export default ShoppingCart |
| Named import |
import { name } from |
import { Product } from './Product' |
| Default import |
import name from |
import ShoppingCart from './Cart' |
| Alias import |
import { name as alias } |
import { Product as Prod } |
| Namespace import |
import * as name |
import * as Models from './models' |
| Re-export |
export * from |
export * from './Product' |
| Type import |
import type { name } |
import type { Product } |