TypeScript में ES Modules
import { name } from "./module";
export const value = expression;
एक Module बनाना
एक TypeScript file ES module बन जाती है जैसे ही यह import या export उपयोग करती है; exported declarations दूसरी files के लिए available हो जाती हैं, जबकि बाकी सब उस file तक private रहता है।
उदाहरण: Creating a Module
// math.ts
export function square(x: number): number {
return x * x;
}
const privateHelper = 42; // not exported, stays private
console.log(square(5));
Named Exports
Named exports एक module को एक साथ कई declarations expose करने देते हैं हर एक के सामने export लिखकर, और importers exactly चुनते हैं कि वे कौन से named exports लाना चाहते हैं।
उदाहरण: Named Exports
// shapes.ts
export const PI = 3.14159;
export function circleArea(radius: number): number {
return PI * radius * radius;
}
console.log(circleArea(2));
Modules Import करना
import statement एक module को दूसरे module द्वारा exported declarations उपयोग करने देता है; imported names exported names से match होने चाहिए जब तक उन्हें rename करने के लिए एक alias उपयोग न किया जाए।
Import paths दूसरी project files, packages, या built-in Node modules की ओर point कर सकते हैं।
उदाहरण: Importing Modules
// shapes.ts
export function circleArea(radius: number): number {
return 3.14159 * radius * radius;
}
// main.ts
// import { circleArea } from "./shapes";
console.log(circleArea(3));
Import Aliases
एक imported declaration को as keyword से rename किया जा सकता है, जो उपयोगी है जब दो modules कुछ एक ही नाम से export करते हैं और दोनों को एक ही file में import करना हो।
उदाहरण: Import Aliases
// shapes.ts
export function area(radius: number): number {
return 3.14159 * radius * radius;
}
// main.ts
// import { area as circleArea } from "./shapes";
const circleArea = area;
console.log(circleArea(4));
Module Organization
Modules बड़े applications को organize करने में मदद करते हैं related declarations को अपनी own file में एक साथ रखकर; एक project का overall structure अक्सर इसके module boundaries को mirror करता है, एक file में एक concern।
उदाहरण: Module Organization
// utils/math.ts
export function double(x: number): number {
return x * 2;
}
// utils/string.ts
export function shout(s: string): string {
return s.toUpperCase() + "!";
}
console.log(double(5), shout("hi"));
importयाexportके बिना एक file को module मानना, जब वह तब एक global script होती है और इसके names global scope में leak हो जाते हैं।- यह भूल जाना कि
privateHelperजैसी एक non-exported declaration दूसरी file से import नहीं की जा सकती। - एक
.tsextension के साथ import करना या"./math"के बजाय"math"जैसा गलत relative path उपयोग करना।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: