Node के साथ TypeScript सेट अप करना
In this page:
npm init -y
npm install --save-dev typescript ts-node @types/node
npx tsc --init
एक TypeScript Project बनाना
Node के लिए एक TypeScript project बनाना package के लिए npm init और npm install --save-dev typescript से शुरू होता है, जो आपको local tsc compiler देता है जिसे आपका project build करने के लिए उपयोग करेगा।
उदाहरण: Creating a TypeScript Project
// npm init -y
// npm install --save-dev typescript
console.log("Project scaffolded with npm init and a local tsc install");
tsconfig.json Configure करना
tsconfig.json configure करना — target, module, और outDir जैसे options set करना — compiler को बताता है कौन सा JavaScript version emit करना है और compiled files को आपके source folder के सापेक्ष कहां रखना है।
उदाहरण: Configuring tsconfig.json
// tsconfig.json
// { "compilerOptions": { "target": "ES2020", "module": "commonjs", "outDir": "dist" } }
console.log("tsconfig.json configures target, module, and outDir");
TypeScript Compile करना
tsc चलाना आपका tsconfig.json पढ़ता है और हर included .ts file को plain .js में compile करता है, साथ में कोई type errors पकड़ते हुए और noEmitOnError enabled होने पर output emit करने से इंकार करते हुए।
उदाहरण: Compiling TypeScript
// tsc
// Reads tsconfig.json, compiles src/*.ts into dist/*.js
console.log("Running tsc compiles .ts files and reports type errors");
Compiled Program चलाना
Compiled output plain ordinary JavaScript है, इसलिए इसे चलाना सिर्फ node dist/index.js है (या जो भी आपका configured outDir हो) — Node खुद कभी TypeScript directly नहीं चलाता, सिर्फ वह JavaScript जो TypeScript produce करता है।
उदाहरण: Running the Compiled Program
// node dist/index.js
console.log("Node runs the compiled JavaScript output, never .ts directly");
Practical Project Structure
एक practical project structure source .ts files को एक src/ folder में और compiled output को एक अलग dist/ folder में रखती है, जो generated JavaScript को version control से बाहर और आपके source tree के रास्ते से दूर रखती है।
उदाहरण: Practical Project Structure
// src/index.ts -> source files (version controlled)
// dist/index.js -> compiled output (gitignored)
console.log("src/ holds TypeScript source, dist/ holds compiled JavaScript");
npm initचलाना और typescript install करना भूल जाना, याtsconfig.jsonबनाने से पहलेtscचलाना।dist/index.jscompile और चलाने के बजायnode src/index.tsचलाना।outDirset करना लेकिनrootDir/includeनहीं, इसलिए compiled files अनपेक्षित folders में जा गिरती हैं।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: