TypeScript के साथ Babel
In this page:
// babel.config.js
module.exports = {
presets: ["@babel/preset-env", "@babel/preset-typescript"],
};
Core Concept
Babel @babel/preset-typescript के through TypeScript syntax compile कर सकता है, जो — esbuild और SWC की तरह — type annotations को validate किए बिना strip करता है, Babel के existing plugin ecosystem (JSX, decorators, आदि) को typed और untyped code दोनों पर uniformly apply होने देते हुए।
उदाहरण: Core Concept
// @babel/preset-typescript strips type annotations, doesn't validate them
console.log("Babel treats TypeScript syntax the same as any other preset");
Basic Setup
एक basic setup babel.config.js में presets array में @babel/preset-env के साथ @babel/preset-typescript add करता है, इसलिए .ts/.tsx files आपके JavaScript जैसी ही pipeline से गुज़रती हैं।
उदाहरण: Basic Setup
// babel.config.js
// presets: ["@babel/preset-env", "@babel/preset-typescript"]
console.log("preset-typescript lets .ts/.tsx pass through Babel's pipeline");
Typed Example
चूंकि Babel सिर्फ types strip करता है, TypeScript-only features जिन्हें compile करने के लिए असल में type information चाहिए — जैसे const enum inlining या legacy experimental decorators का पूरा metadata — Babel के preset के under अलग behave करते हैं या extra flags चाहते हैं।
उदाहरण: Typed Example
// const enum inlining and legacy decorator metadata need extra
// handling under Babel's type-stripping approach.
console.log("Some TypeScript-only features behave differently under Babel");
Project Usage
एक असली project में, TypeScript preset वाला Babel common है जब आप पहले से किसी ऐसी चीज़ के लिए Babel के plugin ecosystem पर depend करते हैं जो tsc अकेले नहीं करता, जैसे custom JSX transforms या बहुत पुराने browsers target करना।
उदाहरण: Project Usage
// Useful when you already depend on Babel's JSX/plugin ecosystem
console.log("Babel + TypeScript preset fits projects with existing Babel plugins");
Best Practices
असली type checking के लिए हमेशा Babel compilation के साथ tsc --noEmit चलाएं, और यह जानें कि कुछ valid TypeScript patterns (merging के लिए उपयोग किए namespaces, कुछ enum forms) Babel के type-stripping approach से पूरी तरह support नहीं होते।
उदाहरण: Best Practices
// package.json: "typecheck": "tsc --noEmit"
console.log("Always run tsc --noEmit alongside Babel for real type checking");
- Babel से type-check होने की उम्मीद करना, जब
@babel/preset-typescriptसिर्फ types strip करता है। const enumयाnamespacemerging उपयोग करना जिन्हें Babel पूरी तरह support नहीं कर सकता।- Babel CLI पर
--extensions ".ts,.tsx"छोड़ देना, इसलिए TypeScript files ignore होती हैं।
- Webpack, Vite, Rollup, और ESBuild सभी TypeScript projects bundle कर सकते हैं।
- SWC और Babel additional tools हैं जो TypeScript compile कर सकते हैं।
- हर tool का अपना setup है, इसलिए right choice आपके project की ज़रूरतों पर depend करती है।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: