Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
⚡ Days 15–22 – Advanced और Async JavaScript  ·  दिन 21

दिन 21: Modules, npm और Modern Tooling

⏱ 90 min📶 Intermediate → Pro🎯 100% self-study
दिन 21 / 30

✅ आज आप सीखेंगे

  • एक बड़ी script.js क्यों संभालना मुश्किल हो जाती है
  • ES modules: named और default export/import
  • Browser (type="module") और Node.js में modules
  • npm, package.json, dependencies और scripts
  • Dev और build के लिए Vite; quality के लिए ESLint + Prettier

🏢 असली दुनिया में

हमारे shop code में अब products, cart class, formatting helpers, validation नियम और API calls हैं – एक file में 900 lines। एक साथ edit करने वाले दो developers एक-दूसरे का काम overwrite करते हैं, और कुछ मिलता नहीं। हर company code को modules में बाँटती है और npm tools इस्तेमाल करती है। Job के पहले दिन आप यही setup देखेंगे।

एक file से modules तक

Folder – a modular shop
sharma-shop/
├── index.html
├── package.json
└── src/
    ├── main.js            ← entry point: wires everything together
    ├── api.js             ← fetchJSON, getProducts, placeOrder
    ├── cart.js            ← export class Cart
    ├── format.js          ← export rupees(), formatDate()
    ├── validate.js        ← export rules, validate()
    └── ui/
        ├── productGrid.js
        └── cartPanel.js

export और import

JavaScript – src/format.js (named exports)
export const GST_RATE = 0.05;

export function rupees(amount) {
  return new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 0 }).format(amount);
}

export const withGst = (amount) => Math.round(amount * (1 + GST_RATE));
JavaScript – src/cart.js (default export)
import { withGst } from './format.js';

export default class Cart {
  #items = [];
  add(product, qty = 1) { this.#items.push({ ...product, qty }); return this; }
  get total() { return withGst(this.#items.reduce((s, i) => s + i.price * i.qty, 0)); }
}
JavaScript – src/main.js
import Cart from './cart.js';                    // default import – any name you like
import { rupees, GST_RATE } from './format.js';   // named imports – exact names in { }
import * as format from './format.js';           // everything as one object

const cart = new Cart().add({ name: 'Kaju Katli', price: 900 }, 2);
console.log(`Total with ${GST_RATE * 100}% GST: ${rupees(cart.total)}`);
console.log(format.withGst(1000));
JavaScript
// The same idea running in Node.js: an inline module demo using data: URLs
const formatModule = `
  export const rupees = n => '₹' + n.toLocaleString('en-IN');
  export default function gst(n) { return Math.round(n * 1.05); }
`;
const url = 'data:text/javascript,' + encodeURIComponent(formatModule);
import(url).then(({ default: gst, rupees }) => {          // dynamic import() returns a promise
  console.log(rupees(gst(180000)));
});
₹1,89,000
प्रकारExportImportकब
Namedexport function rupees() {}import { rupees } from './format.js'हर file में कई helpers (सबसे आम)
Defaultexport default class Cart {}import Cart from './cart.js'हर file में एक मुख्य चीज़ (components, classes)
नाम बदलनाexport { a as b }import { rupees as inr } from …नामों का टकराव रोकना
Namespace—import * as fmt from './format.js'Helpers को group करना
Dynamic—const m = await import('./chart.js')भारी code सिर्फ़ ज़रूरत पर

Browser और Node में modules

HTML – loading a module
<!-- type="module" = deferred automatically, strict mode, own scope, import/export allowed -->
<script type="module" src="src/main.js"></script>
⚠️ Modules को web server चाहिए

Double-click (file://) से index.html खोलने पर security के कारण module imports रुक जाते हैं। VS Code Live Server, npx serve या Vite लें। Browser imports में हमेशा .js extension लिखें।

BrowserNode.js
ES modules चालू<script type="module">package.json में "type": "module", या .mjs files
पुराना formatGlobal scriptsCommonJS: require() / module.exports
npm packagesBundler (Vite) या CDN URLs सेimport express from "express"
Top-level awaitहाँहाँ (ES modules में)

npm और package.json

Terminal – starting a project
# 1. Install Node.js LTS from nodejs.org (includes npm), then check:
node -v
npm -v

# 2. Create a project
mkdir sharma-shop && cd sharma-shop
npm init -y                       # creates package.json

# 3. Add packages
npm install dayjs                 # dependency – shipped with your app
npm install -D vite eslint prettier   # devDependencies – tools for developers only

# 4. Run a script defined in package.json
npm run dev
package.json – the project’s ID card
{
  "name": "sharma-shop",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "lint": "eslint src",
    "format": "prettier --write src"
  },
  "dependencies": {
    "dayjs": "^1.11.13"
  },
  "devDependencies": {
    "eslint": "^9.15.0",
    "prettier": "^3.3.3",
    "vite": "^5.4.11"
  }
}
File / folderGit में commit?क्यों
package.jsonहाँProject को क्या चाहिए
package-lock.jsonहाँसटीक versions – हर developer और server पर एक जैसा install
node_modules/नहीं – .gitignore मेंबहुत बड़ा; npm install / npm ci से दोबारा बनता है
dist/आमतौर पर नहींBuild output; npm run build बनाता है
🧠 ^1.11.13 का मतलब?

Semantic versioning: MAJOR.MINOR.PATCH। ^ नए minor और patch versions की अनुमति देता है (1.12.0 हाँ, 2.0.0 नहीं) क्योंकि major versions आपका code तोड़ सकते हैं।

Vite: dev server और production build

  1. 1npm create vite@latest sharma-shop -- --template vanilla
  2. 2cd sharma-shop && npm install
  3. 3npm run dev → http://localhost:5173 खोलें – save करते ही reload (hot module replacement)
  4. 4src/ में modules लिखें, npm packages नाम से import करें
  5. 5npm run build → dist/ में optimised, minified files
  6. 6dist/ को Hostinger, Netlify या GitHub Pages पर upload करें
शून्य से deployed modular app तक

ESLint और Prettier: अपने-आप code review

ESLint समस्याएँ ढूँढता है

  • बेकार variables और imports
  • Define से पहले variable का उपयोग
  • === की जगह ==
  • छूटा await / न पहुँचने वाला code

Prettier code format करता है

  • सबके लिए एक जैसा indentation और quotes
  • तय चौड़ाई पर line breaks
  • VS Code में save पर चलता है
  • Code review में style बहस ख़त्म
eslint.config.js – a minimal modern setup
import js from '@eslint/js';
import globals from 'globals';

export default [
  js.configs.recommended,
  {
    languageOptions: { ecmaVersion: 'latest', sourceType: 'module', globals: globals.browser },
    rules: {
      eqeqeq: 'error',
      'no-unused-vars': 'warn',
      'prefer-const': 'error',
    },
  },
];

🏅 आज के Job Skills

✔ Named और default exports से code को ES modules में बाँटना✔ Browser और Node.js में modules load करना✔ npm से packages और scripts संभालना✔ Vite से develop और build; ESLint और Prettier से quality

Practice tasks

🏋️ Practice – ख़ुद करें

Task 1: Day 17 के Cart example को exports/imports के साथ cart.js, format.js और main.js में बाँटकर Live Server से चलाएँ।
Task 2: Vite vanilla project बनाएँ, dayjs install करें और dayjs().add(3, "day") से “Delivery by: Wed, 28 Oct” दिखाएँ।
Task 3: eqeqeq और prefer-const चालू करके Day 13 form code पर npx eslint चलाएँ और हर warning ठीक करें।

Quick quiz

🧠 Quick Quiz – ख़ुद को जाँचें

1. './cart.js' से default export import करें:
Default के लिए braces नहीं।
2. <script type="module"> है…
defer जैसा।
3. Git में क्या commit नहीं करना चाहिए?
npm install से दोबारा बनता है।
4. npm install -D vite vite को install करता है…
सिर्फ़ development के लिए।
5. Vite के साथ npm run build output देता है…
dist/ deploy करें।

Interview corner

💼 Interview Corner

ES modules बनाम CommonJS?

ESM static import/export लेता है, browsers और आधुनिक Node में standard है, tree-shaking और top-level await support करता है, और async load होता है। CommonJS require/module.exports लेता है, synchronous है और Node का मूल format था; interop है पर मिलाते समय सावधानी चाहिए।

Vite जैसा bundler क्यों?

Development में hot reload के साथ modules तेज़ी से देता है, npm imports सुलझाता है, और production के लिए bundle, minify, tree-shake, code split करता है और caching के लिए file names fingerprint करता है।

सारांश

  • हर module की एक ज़िम्मेदारी; दूसरों को जो चाहिए वह export।
  • Helpers के लिए named exports, मुख्य चीज़ के लिए default; HTML में type="module"।
  • npm + package.json + lock file; node_modules कभी commit नहीं।
  • Dev/build के लिए Vite; ESLint bugs ढूँढता है, Prettier format करता है।
➡️ आगे

Day 22: काम के browser APIs – IntersectionObserver, clipboard, share, geolocation, URL parameters और history।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

क्या छोटी sites के लिए Vite चाहिए?
नहीं – छोटे projects के लिए साधारण <script type="module"> files काफ़ी हैं। npm packages, कई files या React चाहिए तब Vite।
npm, yarn या pnpm?
सभी वही packages install करते हैं। npm Node के साथ आता है और ठीक है; teams एक चुनकर उसी पर रहती हैं।
← JavaScript (30 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicदिन 22: काम के Browser APIs आपकी प्रगति: 21 / 30 (70%) · Lesson 22 / 30 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें