Import और Export
In this page:
export { name1, name2 };
export function name(): type {}
import { name1 as alias } from "./module";
import * as ns from "./module";
Named Export Syntax
किसी declaration से पहले export लिखना इसे दूसरे modules के लिए एक named export के रूप में available बनाता है, जिसे दूसरी files फिर एक matching import statement से ला सकती हैं।
एक single file जितने चाहे उतने named exports रख सकती है, हर एक individually या साथ में import किया जा सकता है।
उदाहरण: Named Export Syntax
// utils.ts
export function add(a: number, b: number): number {
return a + b;
}
export const VERSION = "1.0";
console.log(add(2, 3), VERSION);
Multiple Values Import करना
कई named exports एक साथ एक single import statement के अंदर curly braces में import किए जा सकते हैं, हर individual export के लिए एक अलग import line चाहने के बजाय, एक file के imports का top compact और scan करना आसान रखते हुए।
उदाहरण: Importing Multiple Values
// utils.ts
export function add(a: number, b: number) { return a + b; }
export function subtract(a: number, b: number) { return a - b; }
// main.ts
// import { add, subtract } from "./utils";
console.log(add(5, 2), subtract(5, 2));
Export Lists
Declarations पहले लिखी जा सकती हैं और बाद में file के नीचे एक separate export list उपयोग करके export की जा सकती हैं, जो एक module की public surface को एक नज़र में scan करना आसान बना सकता है।
उदाहरण: Export Lists
function add(a: number, b: number) {
return a + b;
}
function subtract(a: number, b: number) {
return a - b;
}
export { add, subtract };
console.log(add(1, 1));
Values Re-export करना
एक module उन declarations को re-export कर सकता है जो इसने खुद किसी दूसरे module से import की थीं, जो scattered exports को एक साथ इकट्ठा करने वाला एक single central entry-point file बनाने के लिए उपयोगी है।
उदाहरण: Re-exporting Values
// math.ts
export function square(x: number) { return x * x; }
// index.ts
// export { square } from "./math";
function square(x: number) { return x * x; }
console.log(square(4));
Type-Only Imports and Exports
import type और export type उपयोग करें जब एक declaration सिर्फ type checking के लिए चाहिए हो, क्योंकि ये type-only imports guaranteed रूप से compiled JavaScript output से पूरी तरह strip हो जाते हैं।
उदाहरण: Type-Only Imports and Exports
interface User {
name: string;
}
export type { User };
// main.ts
// import type { User } from "./user";
const u: User = { name: "Ravi" };
console.log(u.name);
import add from "./utils"जैसे braces के बिना एक named export import करना, जब named exports को{ add }चाहिए।- imported name को exported name से अलग spell करना, जो एक error है, जब तक इसे
asसे rename न किया जाए। - local files के लिए
./prefix भूल जाना, तो compiler इसके बजाय एक package ढूंढता है।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: